国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-19 15:23:09
字體:
來源:轉載
供稿:網友

1.問題描述:通過Origin是http://localhost:4200請求http://localhost:8081的服務,控制臺報錯如下,但是Response為200。客戶端和服務端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.解決方法:在服務端/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注解方式。推薦使用注解,方便。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 苍梧县| 清流县| 突泉县| 镇康县| 岢岚县| 五台县| 大理市| 新津县| 临沭县| 吴桥县| 廉江市| 孝义市| 安龙县| 昌图县| 洛南县| 渑池县| 泰州市| 泸溪县| 灵山县| 扶沟县| 柳州市| 广安市| 陆丰市| 南溪县| 金寨县| 北宁市| 于田县| 牟定县| 罗江县| 铁力市| 马关县| 怀来县| 西乌珠穆沁旗| 兴山县| 阿克苏市| 阿克| 廊坊市| 措勤县| 南江县| 德保县| 大悟县|