【问题标题】:Angular2: Angular-http RequestOptions confusionAngular2:Angular-http RequestOptions 混淆
【发布时间】:2017-08-29 19:06:04
【问题描述】:

我正忙于我的第一个 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 } 而不是 options 作为第三个参数,但仍然得到同样的错误......

我不确定我是否正在寻找解决问题的正确位置,当我在 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

【问题讨论】:

  • let Options 应该是let options(小写O
  • @Günter Zöchbauer 这只是我问题中的一个错字。抱歉现在会解决这个问题,在我的实际代码中不是这样

标签: rest http angular


【解决方案1】:

这原来是后端的 CORS 问题...

【讨论】:

  • 我在 chrome 中显示了一些 cors 问题,但在 Firefox 中没有显示...同意这很令人困惑:D
猜你喜欢
  • 2017-08-29
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
相关资源
最近更新 更多