vue打包部署跨域

王林
王林 原创
2023-05-11 11:00:10 898浏览

前言

在项目开发中,我们往往会面对跨域的问题,因为我们使用的域名和后端的接口所在的域名不一致,所以就会出现跨域问题。在开发环境下,我们可以通过配置proxy代理解决跨域问题,但是在打包部署后,就需要使用其他方法解决跨域问题了。本文将介绍如何使用vue-cli3打包部署跨域。

一、什么是跨域

跨域(Cross-Origin Resource Sharing,简称CORS)是浏览器的同源策略的限制,导致网页不能从其他源获取资源,而同源即指两个页面有完全相同的协议、域名和端口号。如果一个请求从非同源的源路径下发起,浏览器就会拒绝请求。

二、vue-cli3打包的几种模式

在vue-cli3中,打包分为三种模式:

  1. 测试模式(build-test)
    测试模式会将我们的代码打包成开发环境下可以运行的模式,并且自动开启sourcemap调试功能。
  2. 生成模式(build-prod)
    生成模式会将我们的代码进行压缩、混淆等处理,适用于部署到生产环境中。
  3. 生成并预览模式(serve)
    serve模式会将我们的代码进行热更新,并且提供一个预览服务,适用于开发时的预览和测试。

三、打包部署跨域解决方案

在打包部署跨域时,我们需要使用nginx来进行反向代理解决跨域问题。

nginx是一款高性能的web服务器,可以在windows、 linux、mac 等各种操作系统上运行。它的功能非常强大,可以用于反向代理、负载均衡、缓存等等。

  1. 安装nginx

在Linux环境下,我们可以通过以下命令来安装nigix:

sudo apt-get update
sudo apt-get install nginx
  1. 配置nginx

在安装完nginx之后,我们需要配置nginx来解决跨域问题。

首先,我们需要找到nginx的配置文件,一般情况下在/etc/nginx/conf.d/default.conf,我们通过以下命令打开nginx的配置文件:

sudo vim /etc/nginx/conf.d/default.conf

然后找到server段,如下:

server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;
        #access_log  /var/log/nginx/host.access.log  main;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ .php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
    }

我们需要在location段下进行反向代理的配置,例如:

location /api {
            proxy_pass http://192.168.0.100:8080; # 后端API地址
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_http_version 1.1;
            proxy_connect_timeout 600;
            proxy_read_timeout 600;
            proxy_send_timeout 600;
            proxy_buffer_size 64k;
            proxy_buffers 4 64k;
            proxy_busy_buffers_size 128k;
            proxy_temp_file_write_size 128k;
            # 解决跨域
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
            # 缓存时间,单位秒。这里设置的是6小时
            expires 21600s;
            # 收到304响应后,再次请求的时间间隔
            proxy_cache_valid 200 304 12h;
        }

其中,proxy_pass后面的地址要改为你的后端API地址,add_header解决的是跨域问题。

  1. 修改vue.config.js配置

在vue-cli3中,我们可以通过在vue.config.js中配置publicPath来让打包后的文件不依赖于域名,具体配置如下:

module.exports = {
  publicPath: '',
  devServer: {
    // 设置跨域代理
    proxy: {
      '/api': {
        target: 'http://192.168.0.100:8080', // 后端API地址
        ws: true,
        changOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  chainWebpack: (config) => {
    config.optimization.delete('splitChunks');
  }
}

其中,/api是后端API地址的前缀,target配置的是后端API地址。

  1. 打包部署

经过以上的配置后,我们就可以打包部署vue项目了。在打包完成后,我们将/dist目录下的文件全部拷贝到nginx配置的根目录下,一般情况下是/usr/share/nginx/html,然后我们重启nginx服务:

sudo service nginx restart

至此,我们已经成功实现了vue-cli3打包部署跨域。

总结

本文介绍了如何使用nginx反向代理来解决vue-cli3打包部署跨域问题。通过上述的配置,我们可以解决跨域问题,并且在生产环境下进行部署。当然,在部署过程中我们需要注意安全问题,例如:开启nginx的用户访问权限等。当然,我们还可以使用其他方法来解决跨域问题,例如:jsonp、websocket等。

以上就是vue打包部署跨域的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。