【问题标题】:Angular HttpClient make GET request with JSON in the bodyAngular HttpClient 在正文中使用 JSON 发出 GET 请求
【发布时间】:2019-08-06 18:32:08
【问题描述】:

我正在开发一个 Angular 客户端应用程序和一个 ASP.NET Core Web API 后端,我在尝试从 Angular 调用工作时遇到了问题,而 Postman 似乎可以正常工作。

打字稿代码:

 exportScript(commands: ScriptCommand[]) {
    this.http.post(this.baseUrl + 'api/ScriptCommands/GenerateScript', JSON.stringify(this.scriptCommands)).subscribe();
  }

C# API 调用:

    [HttpGet]
    [Route("api/ScriptCommands/GenerateScript")]
    public IActionResult GenerateScript([FromBody]List<ScriptCommandViewModel> commands)
    {
        var mappedCommands = MapCommands(commands);
        var stream = ProcessCommands(mappedCommands);
        return File(stream, "application/xml", "generatedScript.xml");
    }

当我使用 Angular 调用时,我收到了 400 Bad Request,但如果我将 JSON 字符串化的 scriptCommand 列表复制到 Postman 请求的正文中,它就可以正常工作。

谢谢大家的帮助!

更新:更改了 Typescript 代码 - 我仍然收到 HTTP 400 错误请求响应,但我在 Chrome 中的网络选项卡在请求标头中显示了这一点 - 内容类型是“文本/纯文本”问题吗?

Accept: application/json, text/plain, */*
Content-Type: text/plain
Origin: http://localhost:4200
Referer: http://localhost:4200/createScript
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36

【问题讨论】:

  • 你为什么不把get方法改成post方法?
  • Http Get 不支持消息体。使用 http get 发送数据的唯一方法是使用 URI 或 Http Header(也包括 cookie)。如果您想发送 json,我会将您的 get 切换到帖子。
  • 我会使用 POST,但我的 API 上的 POST 请求存在单独的 CORS 问题。而如果 HTTP Get 不支持消息体,Postman 是怎么做的呢?
  • 我的立场是正确的,显然你可以,但我认为 Angular 没有任何方法可以做到这一点。参数在 http get 调用中作为 url 查询字符串参数发送。另见stackoverflow.com/a/983458/1260204
  • github.com/angular/angular/issues/9927,浏览器不支持 XHR GET 中的正文

标签: angular asp.net-web-api2


【解决方案1】:

通过在请求 url 中附加请求发送数据, 所以如果你有一个像 {"page":1,"search":"new products"} 这样的 json 正文。 要在获取请求中发送此数据,您可以使用以下代码。

get(path: string, params: any) {
    return this._http.get(this._baseUrl + path, { params: params })
      .pipe(timeout(CONST.API_TIMEOUT));
  }

这将是创建请求 url 之类的(可以在网络选项卡的控制台中验证)

http://localhost:5003/api/auth/test?page=1&search=new products

【讨论】:

    【解决方案2】:

    尝试使用标题中的内容类型进行测试

    来自

    'Content-Type': 'application/json'
    

    'Content-Type': 'application/json;charset=utf-8'
    

    【讨论】:

      【解决方案3】:

      我认为 .append 的工作方式与我们想象的有些不同。 Append 返回附加的 HttpParams。试试这个:

       exportScript(commands: ScriptCommand[]) {
          let httpParams = new HttpParams();
          httpParams  = httpParams.append("commands", JSON.stringify(this.scriptCommands));
          this.http.get(this.baseUrl + 'api/ScriptCommands/GenerateScript', { params: httpParams }).subscribe();
        }
      

      【讨论】:

        猜你喜欢
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-27
        • 1970-01-01
        • 1970-01-01
        • 2020-10-10
        相关资源
        最近更新 更多