Nginx配置跨域请求 Access-Control-Allow-Origin


Nginx配置跨域请求 Access-Control-Allow-Origin *

当出现403跨域错误的时候 No ‘Access-Control-Allow-Origin’ header is present on the requested resource,需要给Nginx服务器配置响应的header参数:

1
2
3
4
5
location / {  
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
}
  1. Access-Control-Allow-Origin

服务器默认是不被允许跨域的。给Nginx服务器配置Access-Control-Allow-Origin *后,表示服务器可以接受所有的请求源(Origin),即接受所有跨域的请求。

  1. Access-Control-Allow-Headers 是为了防止出现以下错误:

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

这个错误表示当前请求Content-Type的值不被支持。其实是我们发起了”application/json”的类型请求导致的。

  1. Access-Control-Allow-Methods 是为了防止出现以下错误:

Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.