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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30038111/article/details/84844842
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);
    }
    

猜你喜欢

转载自blog.csdn.net/qq_30038111/article/details/84844842