Nuxt项目部署到Nginx在本地配置跨域成功但是在nginx上配置了依旧存在跨域问题

新手上路,请多包涵

问题描述

我在使用Nuxt.js开发项目的时候在nuxt.config.js配置了porxy解决了跨域的问题,但是在把项目放到服务器上后又出现了跨域的问题,在Nginx的配置文件中使用了反向代理,但是依旧存在跨域的问题。

问题出现的环境背景及自己尝试过哪些方法

分别对nuxt.js和nginx做了跨域的配置,但是没有成功。

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)
nuxt.config.js:

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  axios: {
   proxy: true, // 开启proxy
    credentials: true,//认证信息
    baseURL: `http://${process.env.HOST || 'localhost'}:${process.env.PORT||3000}`,
    headers: {
      'Content-Type':'application/json; charset=utf-8'
    }
  },
  proxy: {
    '/users': {
      target: 'http://www.shenchangbin.top',
      changeOrigin: true,
      pathRewrite: {  //重写地址
        '^/users' : '/users'
      }
    },
    '/blog': {
      target: 'http://www.shenchangbin.top',
      changeOrigin: true,
      pathRewrite: {  //重写地址
        '^/blog' : '/blog'
      }
    }
  },

nginx.conf:

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
    #gzip  on;

    #负载均衡服务器
    upstream nodenuxt {
        server localhost:3000; #nuxt项目 监听端口
        keepalive 64;
    }

server {
        listen 80;
        server_name  www.shenchangbin.top;
        
        location / {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
        add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

        if ($request_method = 'OPTIONS') {
            return 204;
        }
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;  
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Nginx-Proxy true;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://nodenuxt; #反向代理
        }
        access_log  /etc/nginx/access.log  main;
    }
    include /etc/nginx/conf.d/*.conf;
}

你期待的结果是什么?实际看到的错误信息又是什么?

报错截图:图片描述

又碰到类似问题的嘛?望告知,谢谢

阅读 5.3k
1 个回答

nginx代理应该没问题
我看了下你的所有接口请求地址都是localhost:3000
如图
图片描述

你检查一下axiosbeseURL配置是否有问题.就是这里

图片描述

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