在使用nginx部署vue项目时,使用的是前后端分离的方式部署vue,采用nginx反向代理部署的,但是当我把打包后的文件放入 /nginx/html/文件下时,然后再将nginx的配置文件修改如下:
这里我是在宝塔面版里面直接修改的配置文件
server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } #error_page 404 /404.html; include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /\. { deny all; } access_log /www/wwwlogs/access.log; }我刷新之后,就变成如下页面: 这里有两个问题,一个是,发送的请求报404,并且路由跳转的时候,出现404的情况。
首先我们需要分析,vue-cli的配置文件vue.config.js,这里说的就是为了解决跨域写的配置文件。vue-cli官网的说法:如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。
module.exports = { devServer: { proxy: { '/api': { target: '<url>', ws: true, changeOrigin: true }, '/foo': { target: '<other_url>' } } } }可以发现为了解决跨域问题,vue在启动项目的时候也启动了一个node写的内置服务器,域名和端口是:localhost:8080,细心的小伙伴可以发现,vue ui 界面就是这个地址,当使用axios发送请求时,vue会帮你把请求的端口拼接到 localhost:8080 后面,如:http://localhost:8080/category 这种形式,并且再把这个地址的域名和端口号替换成 target属性中的端口号入下:
假如访问的是 /api/category 这个接口。 首先vue会将这个接口变成:http://localhost:8080/api/category。 然后vue会根据vue.config.js 中配置target属性值来替换请求,变成:htttp://test.com:3000/category,这样就解决了跨域,因为vue里面这个服务器也是用nodejs写的,之间通信不需要跨域,而页面访问的接口,都是localhost:8080这个端口,就不存在跨域了。
module.exports = { devServer: { proxy: { '/api': { target: 'htttp://test.com:3000/',//服务器的请求地址 ws: true, changeOrigin: true, pathRewrite: { '/api': '', // 这里就是替换方法,把路由中的api替换为空 } } } }上面讲了跨域的原理,这是我们可以发现,其实搭建vue项目还要发送一次请求,但是我们再nginx中确没有写代理,并且这里的另外一个问题,就是使用vue中的vue-router写的路由访问不了。这是因为:在vue中使用的是js渲染的虚拟目录,而在nginx配置中并没有实际的资源,所有会出现404。
在nginx中添加配置:
server { #代理80端口 listen 80; server_name localhost; location / { root html; index index.html index.htm; try_files $uri $uri/ @router; } location @router { rewrite ^.*$ /index.html last; } #正向代理vue中转发的请求 #找到以 /api 结尾的请求 location ^~ /api/ { proxy_pass http://127.0.0.1:3000/; } #error_page 404 /404.html; include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /\. { deny all; } access_log /www/wwwlogs/access.log; }这样就能正常访问了
假如出现这样的问题: 这个可能是配置nginx出了问题:需要仔细看一下 出现问题的主要原因是nginx配置异常,没有正确转发后端接口地址。