項目: 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