CORS-接口跨域问题withCredentials
我发现,换个后端开发人员,很可能就会遇到一次跨域问题。然后后端同学就会拿出postman. 说接口可以请求通的,让我们自己解决(跨域是浏览器做的限制,postman又没做限制)。最后的最后还是发现是要他们解决一下。 记录一下,很多时候大多数后端同学根据网上配置后 仍然存在跨域的原因。
是前端请求的时候需要让我们带上用户信息,所有我们有加上withCredentials: true;
这个时候后端同学配置的Access-Control-Allow-Origin: * 就不行了
需要配置,访问的是什么就设置为什么
后端
httpResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true")
前端
$.ajax({ url: "http://localhost:8080/orders", type: "GET", xhrFields: { withCredentials: true }, crossDomain: true, success: function (data) { render(data); } })
参考: