1.問題描述:通過Origin是http://localhost:4200請(qǐng)求http://localhost:8081的服務(wù),控制臺(tái)報(bào)錯(cuò)如下,但是Response為200??蛻舳撕头?wù)端IP相同,但是端口不同,存在跨域問題。
代碼如下:
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ā)送請(qǐng)求http://localhost:8081/api/v1/...,請(qǐng)求成功。且響應(yīng)頭增加了Access-Control-Allow-Credentials和Access-Control-Allow-Origin參數(shù)。@CrossOrigin注解即是給響應(yīng)頭增加了這兩個(gè)參數(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);
報(bào)錯(cuò)如下:
5.查看響應(yīng)碼415,錯(cuò)誤原因:
"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'text/plain;charset=UTF-8' not supported"
6.進(jìn)一步查看請(qǐng)求頭信息,content-type為text/plain。與Response Headers的Content-Type:application/json;charset=UTF-8類型不匹配,故報(bào)錯(cuò)。
7.指定請(qǐng)求頭content-type為application/json,比如在Angular中增加Headers。發(fā)送Post請(qǐng)求,請(qǐng)求成功。
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("====請(qǐng)求staffCreateURL成功并返回?cái)?shù)據(jù)start==="); console.log(responseInfo); console.log("====請(qǐng)求staffCreateURL成功并返回?cái)?shù)據(jù)end==="); let staffName = responseInfo.responseInfo.staffName; console.log(staffName); return responseInfo; })
另:也可以在HttpServletResponse對(duì)象通過setHeader("Access-Control-Allow-Origin", "*")方法增加響應(yīng)頭參數(shù),解決跨域問題,即是@CrossOrigin注解方式。推薦使用注解,方便。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com