1. 程式人生 > >Failed to load resource: the server responded with a status of 403

Failed to load resource: the server responded with a status of 403

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指定不恰當或者後端要求資料格式不匹配引起的

  1. 後端不要求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());
    }
    
  2. 後端要求是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);
    }