与来自nginx的422状态码的响应缺乏“访问控制允许来源”标题
问题描述:
nginx的配置如下:与来自nginx的422状态码的响应缺乏“访问控制允许来源”标题
server {
listen 80;
listen [::]:80;
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT, PATCH';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Max-Age' 1728000;
server_name erp.dev.thinkerx.com;
access_log /home/thinkerx/nginx/access.log;
error_log /home/thinkerx/nginx/error.log;
location ~ /.well-known {
allow all;
}
# The rest of your server block
root /usr/share/nginx/html/men2017-back-dev/public;
index index.html index.htm index.php;
location /api/ {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
js代码如下:
$.ajax({
type: 'post',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
url: "http://erp.dev.thinkerx.com/api/external/material/catalogs",
data: JSON.stringify({
domain_id: 2222,
code:'X01',
name:'123063'
}),
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
console.log(xhr, status, error);
},
});
然后,在发送请求浏览器,Chrome控制台显示两个请求。所述第一请求是预检,方法是OPTION。第二个是真正的请求和响应具有,其状态代码是201 preflight request
{"data":{"id":"16b7d6a0-9eb6-42ca-9ddb-fc61f5e082c0","domain_id":2222,"name":"1230464","code":"X01","parent_id":null,"created_at":1504698369,"updated_at":1504698369}}
如上,事情的预期,但我更新AJAX数据。
$.ajax({
type: 'post',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
url: "http://erp.dev.thinkerx.com/api/external/material/catalogs",
data: JSON.stringify({
domain_id: 2222,
code:'X01',
// name:'123063'
}),
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
console.log(xhr, status, error);
},
});
我再次发送请求。偶然发生错误。 also two requests, the second status code is 422
{ “消息”: “验证失败”, “错误”:[[ “键名称必须是 本”]] “STATUS_CODE”:422}
的XMLHttpRequest不能加载 http://erp.dev.thinkerx.com/api/external/material/catalogs 。否 “访问控制 - 允许来源”标题出现在请求的 资源中。因此不允许访问原产地'http://localhost'。 响应了HTTP状态代码422
我有一些问题如下:
- 为什么报告同源策略的错误?
- 我看到控制台响应,为什么AJAX xhr.responseJSON是不确定的?如何获取响应?
答
我有同样的问题。问题是nginx仅为200,204,301,302和304状态码添加标题。
要获得相同的头文件对每种类型的状态代码,你必须[总是]添加在这样add_header指令的结束。
add_header 'Access-Control-Allow-Origin' $http_origin always;
希望它会帮助你)