CORS跨域请求
允许跨域请求
只需要在服务器设置响应头Access-Control-Allow-Origin, 不然的话可以从服务器拿到响应,但是浏览器不会把这个响应显示出来。
(index):1 Access to XMLHttpRequest at 'http://localhost:9001/demo/name' from origin 'http://localhost:9002' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
方案:
response.setHeader("Access-Control-Allow-Origin", "http://localhost:9002");
请求响应中会携带:Access-Control-Allow-Origin: http://localhost:9002
访问成功,可以获取数据。
Access-Control-Allow-Origin: http://localhost:9002 Content-Length: 6 Content-Type: text/html;charset=UTF-8 Date: Fri, 01 Nov 2019 01:24:33 GMT
跨域请求携带cookie
//服务器端允许跨域请求携带cookie。
response.setHeader("Access-Control-Allow-Credentials", "true");
# 同源访问,会携带cookie。但是不同源的访问服务器不会响应cookie。尽管代码中设置了。 # http://localhost:9001/demo/name Access-Control-Allow-Origin: http://localhost:9002 Content-Length: 6 Content-Type: text/html;charset=UTF-8 Date: Fri, 01 Nov 2019 01:24:33 GMT Set-Cookie: age=25 # 不同源访问,并没有返回cookie Access-Control-Allow-Origin: http://localhost:9002 Content-Length: 6 Content-Type: text/plain;charset=UTF-8 Date: Fri, 01 Nov 2019 01:15:22 GMT
/*
服务端
*/
@RestController
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/name")
public String name(HttpServletResponse response){
response.setHeader("Access-Control-Allow-Origin", "http://localhost:9002");
// response.setHeader("Access-Control-Allow-Credentials", "true");
return "刘备";
}
}
bugs
Access to XMLHttpRequest at 'http://localhost:9001/demo/name' from origin 'http://localhost:9002' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. # 请求头 Accept: */* Origin: http://localhost:9002 Referer: http://localhost:9002/ Sec-Fetch-Mode: cors User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36 # 响应头 Content-Length: 6 Content-Type: text/plain;charset=UTF-8 Date: Thu, 14 Nov 2019 00:35:24 GMT # 响应体 刘备 现象:浏览器可以拿到服务器的响应但是因为浏览器的同源策略,浏览器不会把响应给js代码。