1.問題描述:通過Origin是http://localhost:4200請求http://localhost:8081的服務,控制臺報錯如下,但是Response為200。客戶端和服務端IP相同,但是端口不同,存在跨域問題。
2.解決方法:在服務端/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/...,請求成功。且響應頭增加了Access-Control-Allow-Credentials和Access-Control-Allow-Origin參數。@CrossOrigin注解即是給響應頭增加了這兩個參數解決跨域問題。

4.在服務端POST方法同樣使用注解@CrossOrigin解決跨域問題。
@CrossOrigin(origins = "*", maxAge = 3600)@RequestMapping(value = "/api/v1/staffs", produces = { "application/json" }, method = RequestMethod.POST)RestResponse<?> createStaff(@RequestBody RestRequest<StaffReqInfo> request);報錯如下:

5.查看響應碼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成功并返回數據start==="); console.log(responseInfo); console.log("====請求staffCreateURL成功并返回數據end==="); let staffName = responseInfo.responseInfo.staffName; console.log(staffName); return responseInfo;})另:也可以在HttpServletResponse對象通過setHeader("Access-Control-Allow-Origin", "*")方法增加響應頭參數,解決跨域問題,即是@CrossOrigin注解方式。推薦使用注解,方便。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答