欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular客戶端請求Rest服務(wù)跨域問題的解決方法

 更新時間:2017年09月19日 14:15:58   作者:sean  
本篇文章主要介紹了Angular客戶端請求Rest服務(wù)跨域問題的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下

1.問題描述:通過Origin是http://localhost:4200請求http://localhost:8081的服務(wù),控制臺報錯如下,但是Response為200??蛻舳撕头?wù)端IP相同,但是端口不同,存在跨域問題。

復(fù)制代碼 代碼如下:

XMLHttpRequest cannot load http://localhost:8081/api/v1/staffs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

2.解決方法:在服務(wù)端/api/v1/staffs的Restful方法增加@CrossOrigin注解,比如:

@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "/api/v1/staffs", produces = { "application/json" }, method = RequestMethod.GET)
RestResponseList<?> queryStaffs(@RequestParam(value = "limit", required = false, defaultValue = "20") int limit,
 @RequestParam(value = "offset", required = false, defaultValue = "0") int offset);

3.重新發(fā)送請求http://localhost:8081/api/v1/...,請求成功。且響應(yīng)頭增加了Access-Control-Allow-Credentials和Access-Control-Allow-Origin參數(shù)。@CrossOrigin注解即是給響應(yīng)頭增加了這兩個參數(shù)解決跨域問題。

4.在服務(wù)端POST方法同樣使用注解@CrossOrigin解決跨域問題。

@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "/api/v1/staffs", produces = { "application/json" }, method = RequestMethod.POST)
RestResponse<?> createStaff(@RequestBody RestRequest<StaffReqInfo> request);

報錯如下:

5.查看響應(yīng)碼415,錯誤原因:

"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'text/plain;charset=UTF-8' not supported"

6.進一步查看請求頭信息,content-type為text/plain。與Response Headers的Content-Type:application/json;charset=UTF-8類型不匹配,故報錯。

7.指定請求頭content-type為application/json,比如在Angular中增加Headers。發(fā)送Post請求,請求成功。

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers });

return this.http.post(this.staffCreateURL, body, options).map((response: Response) => {
 //return this.http.get(this.userLoginURL).map((response:Response)=> {
 let responseInfo = response.json();
 console.log("====請求staffCreateURL成功并返回數(shù)據(jù)start===");
 console.log(responseInfo);
 console.log("====請求staffCreateURL成功并返回數(shù)據(jù)end===");
 let staffName = responseInfo.responseInfo.staffName;
 console.log(staffName);
 return responseInfo;
})

另:也可以在HttpServletResponse對象通過setHeader("Access-Control-Allow-Origin", "*")方法增加響應(yīng)頭參數(shù),解決跨域問題,即是@CrossOrigin注解方式。推薦使用注解,方便。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論