我在前端使用 Weblow (www.example.com) 和一个单独的服务器通过 JSON (api.example.com) 提供后端数据。
我使用Nginx,我的配置如下:
server {
server_name api.example.com;
index file.json;
location / {
root /var/www/example/html;
default_type application/json;
add_header Content-Type application/json;
add_header Access-Control-Allow-Methods "*";
add_header Access-Control-Allow-Methods "*";
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by Certbot
include /etc/l
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "*";
if ($host = api.example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name api.example.com;
return 404; # managed by Certbot
}
我的前端代码如下所示:
var xmlhttp = new XMLHttpRequest();
var url = "https://api.example.com";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xmlhttp.send();
但是我的请求已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 然而,我的请求仍然被 CORS 阻止。
想知道我上面的代码有什么问题吗?
提前非常感谢。
我尝试在 Nginx 中添加允许 CORS 的标头,但不起作用。
我解决了。我的 Nginx 配置如下所示:
location / {
add_header Content-Type application/json;
add_header Access-Control-Allow-Methods "*";
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Headers "*";
if ($request_method = OPTIONS){
return 204;
}
root /var/www/cryptogossip/html;
default_type application/json;
}