Failed to load resource: the server responded with a status of 403 ()
personList.html:1 Failed to load http://192.168.0.103/person/getList:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:8020' is therefore not allowed access. The response had HTTP status code 403.
前後端聯調時,出現如上的錯誤,可能是因為
contentType
指定不恰當或者後端要求資料格式不比對引起的
- 後端不要求
格式,但是前端是json
json
格式
前端:
後端:$(function(){ $.ajax({ type:"get", url:"http://192.168.0.103/person/getList", dataType:"json", contentType:"application/json;charset=utf-8", success:function(result){ alert(result); } }); });
@RequestMapping(value = "/getList", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResultBean getList() { return new ResultBean(getData()); }
- 後端要求是
,前端傳的資料是json
表單序列化form
前端:$("#form").serialize()
後端:$(function(){ $.ajax({ type:"post", url:"http://192.168.0.103/person/createByJson", dataType:"json", data:$("#form").serialize(), contentType:"application/json;charset=utf-8", success:function(result){ alert(result); } }); });
@PostMapping(value = "/createByJson", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResultBean createByJson(@RequestBody @Validated Person person) { return new ResultBean(person); }