我忙於使用我的第一個Angular web應用程序,我不得不做一個帖子,我很不確定如何將標題添加到請求中......就我而言在線閱讀的方式是使用angular-http的RequestOptions。我看到很多在線的例子,其中RequestOptions以這種方式使用:Angular2:Angular-http 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的錯誤:
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
我可以用失眠REST客戶端,所以我知道這個問題是不相關的API發佈的API ...
我見過的在線地點RequestOptions使用了我使用它的方式:
https://scotch.io/tutorials/angular-2-http-requests-with-observables
https://angular.io/docs/ts/latest/guide/server-communication.html
'讓Options'應該是'讓options'(小寫'O') –
@君特Zöchbauer那在我的問題中只是一個錯字。對不起將修復現在,它不是這樣在我的實際代碼 – user2094257