项目: vue + express + mongodb
项目先后分离部署在一台服务器上面php
express端口:3000
mongodb端口:27017
vue端口:本地是8080 服务端是:80css
本地开发基于vue cli 端口是 8080若是请求api的时候在前缀加上localhost:3000会提示跨域问题,咱们能够使用下面方式来解决这个问题html
proxyTable: {}
添加以下配置
demo:vue
proxyTable: { '/v1/**':{ target: 'http://localhost:3000/', pathRewrite: { '^/v1': '/' } } }
v1 是我给api自动添加的前缀
这个前缀能够使用 axios 配置添加
在main.js 主入口文件添加
以下ios
import apiConfig from '../config/api.config' // import axios import Axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, Axios) // Axios.defaults.baseURL = apiConfig.baseUrl; Axios.defaults.baseURL = 'v1/' 这样也ok的
api.confignginx
判断是开发模式仍是本地模式,其实不须要这么麻烦 直接 const isProdMode = Object.is(process.env.NODE_ENV, 'production') module.exports = { baseUrl: isProdMode ? 'api.shudong.wang/v1/' : 'v1/' }
若是把axios 配置了自动前缀
每次访问的时候git
data(){ return { articleList:Object } }, mounted: function(){ this.getArticleList() }, methods:{ getArticleList(){ console.log(111111111) this.$http.get("/article/list") // this.$http axios使用的一种方式 .then((response)=>{ console.log(response.data) let res = response.data; this.articleList = res.data; }) .catch((error) =>{ console.log(error) }) } },
上面请求的例子中至关于访问: localhost:8080/v1/article/listgithub
这样就能够解决跨域问题
其实最终访问的是 localhost:3000/article/list express的api
这个v1只是api版本的标识,若是想带着,而且api是能够v1版本方式访问的,把代理的路径从新规则去掉就能够
操做以下:mongodb
proxyTable: { '/v1/**':{ target: 'http://localhost:3000/', //pathRewrite: { //这个规则去掉 // '^/v1': '/' //} }, '/goods/*':{ target:'http://localhost:3000' }, '/users/**':{ target:'http://localhost:3000' } }
本地能够使用proxyTable 解决跨域问题,那么服务端怎么解决跨域问题呢?express
answer:使用nginx反向代理
nginx配置: 仔细分析一下看看是否适合本身的业务场景
server { listen 80; #listen [::]:80; server_name zhenfan.shudong.wang ; # 你的域名不须要加http index index.html index.htm index.php default.html default.htm default.php; root /home/wwwroot/zhenfan/dist; include none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location /v1 { proxy_pass http://127.0.0.1:3000/; # 当访问v1的时候默认转发到 3000端口 } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } access_log off; }
关于express连接mongodb能够直接填写端口号,不存在跨域问题,直接 127.0.0.1:27017就ok,
怎么在服务器上面搭建能够参考上篇 mongodb篇
关于有什么问题,能够在下面留言,但愿你是来讨论技术的。
上次写完一篇,一个小朋友,来到这里咬文嚼字,针对 部署这个词,说用的不当,还口口声声说是来讨论技术,把注意力放在这个上面上真没意义。
但愿本篇文章能帮到你,解决你的问题。
github: wsdo