前端页面访问后端服务跨域解决方案

  • 前端页面向后端发起请求时,出现跨域错误,mark一下,以防再次遇到这类问题
  • 通过XMLHttpRequest发起Post请求:
var data = {
			"enterName":enterName,
			"linkName" :linkName,
			"linkPhone":linkPhone
			};
var url = ip + '/addAdMessage';
   		console.log(url);
		var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.addEventListener("readystatechange", function () {
            if (this.readyState === 4) {
                console.log(this.responseText);
                let data = JSON.parse(this.responseText);
                console.log(data);
                console.log(data.message);
                if (data.code == 200 && data.success) {
                    alert(data.message);
                } else {
                    alert(data.message);
                }
            }
        });
        xhr.open("POST", url);
        xhr.setRequestHeader("Content-Type", "application/jsonp");
        xhr.setRequestHeader("Cache-Control", "no-cache");
        xhr.send(data);
  • 通过jquery ajax发起POST请求:
$.ajax({
   			type:'POST',
   			url:url,
   			dataType:'json',
   			data:JSON.stringify(data),
			headers:{
				"Access-Control-Allow-Origin":"*"
			},
			contentType: "application/json",
   			success:function(result){
				console.log(aaa)
   			}
   		})

发送请求出现如下错误:

about.html:257 http://192.168.3.26:8080/addAdMessage
about.html:279 OPTIONS http://192.168.3.26:8080/addAdMessage 403
about.html:1 Access to XMLHttpRequest at 'http://192.168.3.26:8080/addAdMessage' from origin 'http://127.0.0.1:8848' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

前端使用的静态页面发起请求,后端采用的是Spring boot
在前端页面头中加入


后端接口处允许跨域请求

@CrossOrigin(value = "*", maxAge = 3600, allowCredentials = "true")
//value :允许的值
//maxAge:最大生存时间(单位s)
//allowCredentials :是否允许浏览器发送证书或者其他缓存数据(设置为true就可以了)

重启服务,请求成功

你可能感兴趣的:(java,spring)