vue 打包后 nginx 服务端API请求跨域问题无法解决。

我把vue打包传到服务端后 放在 www 子域名所指定的目录里。当我发起请求的时候要去请求 api 子域名所绑定的目录。这一请求就造成了跨域提示

clipboard.png

然后我在nginx 里也配置了也无解。

clipboard.png

也就是我请求 www.daimatu.cn/api/login/index ajax post 请求 转发到 api.daimatu.cn/api/login/index 去

我之前在 location / {} 和 location /api {} 里做了很多设置 都是网上百度来的,然后并没有用~!

然后我在我本的把请求的地址改为线上的,本地请求也没有问题!是通的能正常操作。我对比了下两边的请求头发现不一样!本地请求线上服务端 Request Method 是正常的GET POST 而我线上从 www 转到请求 api 的 Request Method 变成了 OPTIONS 而不是正常的 GET POST 等请求头 我也搜索找了设置 OPTIONS 怎么设置请求的时候跨域还是无法解决了!

clipboard.png

如图上所示 变成了 options 了

我想请教下大伙 你们是如何配置的。我后端语言是PHP 不要叫我去设置更改PHP。我本地请求本地服务和线上服务都是通的正常的,只有线上www 转发请求 api 有问题。所以不用改程序。

Api 请求地址: http://api.daimatu.cn/api/log...
Api 帐号: admin
Api 密码: 123456
Api 验证码: 1234
求大伙 NGINX服务器请求我这个API过来 看下你们的配置。我已经折腾了半天也没有成功!!

阅读 14.3k
4 个回答

在location中作如下配置

add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

然后重启nginx服务

service nginx reload

参考资料

nginx 配置

#
# 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';
        #
        # 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';
     }
     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';
     }
}

重新载入 nginx 配置

service nginx reload

我现在也遇到这个问题,配置了nginx,但是访问的时候提示404,请问你怎么解决的

回答都是 nginx?那么apache 的怎么解决呢?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题