【发布时间】: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 中的正文