The nginx server is configured to address the cross domain issues of API

  • 2020-05-13 04:30:32
  • OfStack

preface

Recently, a series 1 problem was discovered when calling the http request with jquery ajax:

If you use firebug to debug API request (this API is the application of your own server), you can see that the server clearly returns 200 status, and response returns data in json format, but ajax returns error.

After ruling out the reason for the incorrect json data format, the ajax error function returns "networkerror failed to execute 'send' xmlhttprequest' failed to load' http //" XMLHttpRequest.status =0, which is not initialized.

It turned out to be a cross-domain problem (CORS), because the program was calling API of a remote server, and the server did not allow cross-domain calls. If it's a simple method, just add properties to the response that support cross-domain header." Access-Control-Allow-Origin: * "Can.

For example, java server code:


yourownvariable.setHeader("Access-Control-Allow-Origin:", "origin url of your site");


yourownvariable.setHeader("Access-Control-Allow-Methods", "GET, POST,PUT");

If you are configuring the nginx server (for other servers, please refer to: I want to add support to my server), you need to add 1 to the nginx.conf configuration file:


#
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
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';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
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-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
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-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
}

conclusion


Related articles: