nginx config如下:
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 Console显示两个请求。第一个请求是前飞行,方法为选项。第二个是真实的请求,并具有响应,其状态代码为201。前飞行请求
{"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);
},
});
我再次发送请求。根据情况,发生了错误。另外两个请求,第二个状态代码是422
{" message":"验证失败","错误":[["密钥名称必须为 现在"]]," 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;
希望它对您有帮助)