使用Nginx 反向代理解決跨域問題(vue.js使用代理去掉vue.js因為跨域而觸發的options請求)
創新互聯建站專注于企業網絡營銷推廣、網站重做改版、雨山網站定制設計、自適應品牌網站建設、HTML5、商城系統網站開發、集團公司官網建設、成都外貿網站建設、高端網站制作、響應式網頁設計等建站業務,價格優惠性價比高,為雨山等各大城市提供網站開發制作服務。
我們的項目還是需要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 路由的反向代理到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來解決跨域的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持創新互聯。
分享名稱:vue.js使用代理和使用Nginx來解決跨域的問題
文章位置:http://m.2m8n56k.cn/article16/jdsjdg.html
成都網站建設公司_創新互聯,為您提供定制網站、網站內鏈、網站制作、企業網站制作、靜態網站、做網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯