Angular2:Angular-http RequestOptions混淆

时间:2017-01-13 07:19:17

标签: rest http angular

我正忙着我的第一个Angular网络应用程序,我必须做一个帖子,我很不确定如何将标题添加到请求中...据我在线阅读的方法来做到这一点是通过使用angular-http的RequestOptions。我在网上看到很多以这种方式使用RequestOptions的例子:

我的代码:

let hdrs = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({headers: hdrs});
        return this.http.post(this.API_URL + "StockTake/AddToStockTake", JSON.stringify(stockTakeModel), options)
        .map((res: Response) => res.json())
        .catch((error: any) => Observable.throw(error.json().error || 'server error'));
  }

当我这样做时,我的Chrome控制台总是会出现同样的错误,

Chrome错误:

  Failed to load resource: net::ERR_CONNECTION_RESET

在Firefox中,错误是:

[WDS] Disconnected!
main.bundle.js:51863:10
log
http://localhost:4200/main.bundle.js:51863:10
onSocketMsg.close
http://localhost:4200/main.bundle.js:51912:3
socket/sock.onclose
http://localhost:4200/main.bundle.js:85690:4
EventTarget.prototype.dispatchEvent
http://localhost:4200/main.bundle.js:51108:5
SockJS.prototype._close/<
http://localhost:4200/main.bundle.js:83235:5
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask
http://localhost:4200/main.bundle.js:86029:21
Zone$1</Zone</Zone.prototype.runTask
http://localhost:4200/main.bundle.js:85918:28
ZoneTask/this.invoke
http://localhost:4200/main.bundle.js:86099:28
scheduleTask/data.args[0]

有人向我建议,http post方法的第三个选项采用RequestOptionsArgs类型而不是RequestOptions类型......如果是这样,那么在这个实例中它会如何?我也试过{ headers: hdrs }而不是选项作为第三个参数,但仍然得到相同的错误...

我不确定我是否正在寻找适合我的问题的地方,当我查看Chrome开发工具网络标签中请求的请求标题时,它会列出以下内容:

Provisional headers are shown
Access-Control-Request-Headers:
content-type
Access-Control-Request-Method: POST
Origin: http://localhost:4200
Referer: http://localhost:4200/stockTake
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

我可以使用Insomnia Rest客户端发布到API,所以我知道这个问题与API无关......

我见过的在线地方RequestOptions的使用方式与我一样:

https://scotch.io/tutorials/angular-2-http-requests-with-observables

https://angular.io/docs/ts/latest/guide/server-communication.html

1 个答案:

答案 0 :(得分:1)

事实证明这是后端的CORS问题......