The nginx server configuration addresses the cross domain issues of ajax

  • 2020-05-12 07:00:13
  • OfStack

When calling the http request with jquery ajax, a series 1 problem was found:

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 eliminating the reason for the incorrect json data format, the ajax error function returns "networkerror failed to execute '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 the cross-domain support header add attribute "Access-Control-Allow-Origin: *" to the program's response. 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 CORS 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';
}
}


Related articles: