解决nginx服务器API的跨域问题的方法介绍

前言
  最近在采用jquery ajax调用http请求时,发现了一系列问题:
  如采用firebug调试API请求(这个API是自己服务器的应用),看到服务器明明返回200状态,response返回数据也是json格式,但ajax返回的error。
  在排除json数据格式不正确的原因之后,发现了ajax error函数返回“networkerror failed to execute ‘send’ on ‘xmlhttprequest’ failed to load ‘http //“ XMLHttpRequest.status=0,就是没有初始化。
  后来才知道是跨域问题(CORS),因为程序调用的是远程服务器的API,服务器不允许跨域调用。如果只是简单的方法,只需要在程序的response添加支持跨域的header添加属性”Access-Control-Allow-Origin: * “即可。百度收录批量查询
  如java 服务器代码:
  yourownvariable.setHeader(“Access-Control-Allow-Origin:”, “origin url of your site”);
  yourownvariable.setHeader(“Access-Control-Allow-Methods”, “GET, POST,PUT”);
  如果是配置nginx服务器(如果是其他服务器,可以参考:I want to add CORS support to my server),需要在nginx.conf配置文件添加一下内容:
  #
  # Wide-open CORS config for nginx
  #
  location / {
  if (KaTeX parse error: Double superscript at position 74: …-Allow-Origin' '̲*';   add_heade…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’;
  }
  }
nginx服务器怎麼解决

你可能感兴趣的:(解决nginx服务器API的跨域问题的方法介绍)