vue.js使用代理和使用Nginx來解決跨域的問題,vue.jsnginx
使用Nginx 反向 Proxy解決跨域問題(vue.js使用代理去掉vue.js因為跨域而觸發的options請求)
我們的項目還是需要node.js作為容器的
一、Windows 下安裝Nginx (官網下載穩定版http://nginx.org/en/download.html)
二、修改config裡的nginx.conf檔案的server
server { listen 8899;// 你的連接埠 server_name localhost; root C:/ZOBSF_F/dist;//你打包部署的檔案路徑 #charset koi8-r; #access_log logs/host.access.log main; # 匹配 api 路由的反向 Proxy到API服務 location ^~/api { proxy_pass http://119.23.227.141:10001/;//你的後端IP和連接埠 } #根據路由設定,避免出現404 location / { try_files $uri $uri/ @router; index index.html; } location @router { rewrite ^.*$ /index.html last; } #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 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; #} }
三、 你的uve.js打包的dist檔案如下
四、然後再加一個項目啟動設定檔 server.production.js
var express = require('express');var app = express();var compression = require('compression');var proxyMiddleware = require('http-proxy-middleware')var history = require('connect-history-api-fallback');app.use(compression());app.use(express.static(__dirname));app.middleware = [//使用代理api proxyMiddleware(['/api'], {target: 'http://192.168.11.103:10001', changeOrigin: true, pathRewrite: { '^/api' : '/', },}),];app.get('*', function(req, res) { res.sendFile(__dirname + '/index.html');});app.use(history());app.use(app.middleware);app.listen('8080', function(error) { console.info("==================系統正在啟動中...============================="); if (error) { console.error(error) } else { console.info("==================9999系統啟動成功!!!=============================") }});
五、然後在項目目錄下使用命令node server.production.js 斷行符號發現包缺少依賴,使用npm install [報錯提示的相依元件] 即可 分別有express、compression、http-proxy-middleware等。
然後啟動項目就可以了 訪問地址http://localhost:8080/xxx即可
六、vue.js使用代理具體可以百度(在config設定檔裡的inde.js修改就可了)
proxyTable: { '/api': { target: Host.Host,//設定你調用的介面網域名稱和連接埠號碼 別忘了加http changeOrigin: true, pathRewrite: { '^/api': '/'//這裡理解成用‘/api'代替target裡面的地址,後面組件中我們掉介面時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add'即可 } } },
以上這篇vue.js使用代理和使用Nginx來解決跨域的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。