我正在使用web api後端和angular2前端工程。我遇到了顯示angular2中的服務器錯誤的問題。每當服務器發生錯誤時,都會引發CORS錯誤。在angular2中顯示web api異常
Here is my sample api
public IActionResult Post([FromBody] Visitor model)
{
if (model == null) throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NoContent)
{
ReasonPhrase = "Missing model in post"
});
_registerService.register(model);
return Ok(model);
}
And here is my angular2 service
addVisit(visit: Visit) {
let siteId = visit.siteId;
let body = JSON.stringify(visit);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.authHttp
.post(`${this._visitorsUrl}` + siteId, body, options)
.map(res => {
res.json();
console.log("map: " + JSON.stringify(res.json()));
})
.catch(err => console.log(err));
}
當模型爲null,則返回錯誤502或CORS錯誤,但在模型不爲空,將retrn 200
我的問題是我怎麼能顯示錯誤的服務器返回。
我已經做到了,但仍然不能正常工作 handleError(error:any)let errMsg =(error.message)? error.message: error.status? '$ {error.status} - $ {error.statusText}':'服務器錯誤'; console.error(errMsg); //登錄到控制檯而不是 return Observable.throw(errMsg); } –
在這裏你有另一個基本上做同樣的例子,檢查getCountriesByRegion(),如果它沒有顯示它可能是因爲別的東西? http://www.waynehong.com/javascript/angular-2-service-example-typescript/ –