vue项目打包部署在nginx跨域访问问题

因为浏览器的同源策略,vue项目上线时要部署在服务器,访问webserver时会出现跨域访问问题。
http请求存在简单请求和复杂请求两种,具体原理能够去读阮一峰这篇文章,讲解的很明白。出自http://www.ruanyifeng.com/blog/2016/04/cors.html
一、通常简单请求跨域访问会出现“No ‘Access-Control-Allow-Origin’ header is present on the requested resource“这个问题,后台程序请求头设置header(Access-Control-Allow-Origin,*)能够解决。表明着容许全部的域名请求,也能够根据本身需求设定特定的域名。
二、复杂请求会出现405 method not found 的问题,由于复杂请求会预先发送options请求,获取服务器支持的跨院请求方法。后台这是header(Access-Control-Allow-Origin,
),header(Access-Control-Allow-method,‘POST,PUT,DELETE,OPTIONS’),header(Access-Control-Allow-Headers,‘Authorizations’)均不能解决问题。
具体解决方案是使用nginx设置反向代理。
在vue项目的config/index.js文件配置代理html

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://172.21.4.110:8001',//设置你调用的接口域名和端口号
        changeOrigin: true,     //跨域
        pathRewrite: {
          '^/api': '/'          //这里理解成用‘/api’代替target里面的地址,后面组件中咱们掉接口时直接用api代替 好比我要调用'http://10.1.5.11:8080/xxx/duty?time=2017-07-07 14:57:22',直接写‘/api/xxx/duty?time=2017-07-07 14:57:22’便可
        }
      }
    },
}

开发环境下配置代理后能够发送post请求,可是在生产环境下没法调通。所以我用到了nginx的反向代理。在nginx的配置文件nginx.conf 修改以下:vue

server {
    listen       9527;
    server_name  localhost;
	root   /usr/share/nginx/html/dist;
	index  index.html index.htm;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;
	
	#add_header Access-Control-Allow-Origin *;
	#add_header Access-Control-Allow-Methods POST,GET,OPTIONS;
	#add_header Access-Control-Allow-Headers Authorization;

    location /api/ {
        rewrite ^/b/(.*)$ /$1 break;
		proxy_pass http://172.21.4.110:8001/; **#此处结尾必须有‘/’,否则会出现404 page not found**
    }
}

重启nginx服务,再次发送post请求ios

this.$axios({
              url: ‘/api/a’,
               method:'post',
               headers:{"Authorization":'Basic ' + token}
             }).then(function(return_data){})

此处的URL中/api在nginx中会自动转为http://172.21.4.110:8001/,请求成功。nginx