我们在编写自己的网站时请求一些接口或者网页资源时,可能会遇到请求无响应的现象,这时按F12查看控制台会发现报出了下面这句错误,这其实就是跨域资源共享(CORS)协议阻止了请求。
Access to XNLAttpRequest at 'https://xxx.xxxx.xxx' from origin 'https://xxx.xxx.xxx' has xxx.xx been blocked by coRs policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在Nginx配置文件末尾插入下面配置,保存并重载配置即可
# 允许跨域
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
不想深入研究的,看到这里就可以啦
Access-Control-Allow-Origin *
后,服务器就会接受所有的请求源其中就包括了跨域的请求。Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
错误。这个错误表示当前请求Content-Type的值不被支持。是发起"application/json"的类型请求导致的
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response
错误。在api.php页面的头部插入以下代码就可以,接口跨域共享,网站其他页面不会共享,如果想限制只允许自己调用接口,可以把 * 改成自己的域名要带上http或者https。
<?php
header('Content-Type:text/html;charset=utf-8');
header("Access-Control-Allow-Origin: *");
?>
假设请求的链接是这样的 http://xxxx.xxxx.xxx/abc/api?1234
。
在Nginx里插入这样一条配置
location /abc/ {
proxy_pass http://xxxx.xxxx.xxx;
}
把文件里请求的链接改成 /abc/api?1234
,这时服务请求的实际上是服务器本地的地址即 127.0.0.1:xxxx(端口)/abc/api?1234
,然后就能访问了,原理是跨域问题是浏览器报错阻止了请求,骗过浏览器就能正常访问到。