前言
? 本篇文章主要記錄個人在公司項目開發(fā)中所遇問題,主要內(nèi)容:在vue項目的開發(fā)中圖片所存的服務(wù)器/端口號和項目所在的服務(wù)器/端口號不同,出現(xiàn)了跨域問題的保錯。
? 如果文章有歧義,請各位大佬指出,避免誤導(dǎo)更多的人??!
正文
Bug起因
? 在vue項目的開發(fā)中圖片所存的服務(wù)器/端口號和項目所在的服務(wù)器/端口號不同,在設(shè)置背景圖片時出現(xiàn)了跨域問題的保錯。
Vue項目解決跨域問題
1. 可以通過 vue.config.js 中的 devServer.proxy 選項來配置請求代理。(vue打包部署時代理失效)
devServer: {
// development server port 8000
port: 8000,
// If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
proxy: {
'/api': {
target: 'http://1xx.1xx.1.xx:8080/api',
ws: false,
changeOrigin: true,
pathRewrite: { '^/api': '' }
},
// 解決圖片跨域問題(api請求時注意使用/upload開頭)
'/upload': { // 前端項目要被代理的路徑
target: 'http://1xx.1xx.1.xx:8083', // 真正的圖片路徑
changeOrigin: true, //表示是否改變原域名
ws: true, //表示W(wǎng)ebSocket協(xié)議
pathRewirte: {
// 這里是追加鏈接,比如真實接口/請求路徑里包含了 /upload,就需要這樣配置.
'^/upload': ''
}
}
}
}
? 很明顯 devServer的配置主要針對vue項目本地開發(fā)環(huán)境時的跨域代理配置;當(dāng)vue前端項目打包部署后,會成為單獨的靜態(tài)資源,前端框架中所配置服務(wù)器跨域代理將不起作用;資源要被訪問,那必然還是需要有另一個 web 服務(wù)器來裝載它,這個服務(wù)器常見的就是nginx。
2.nginx服務(wù)器反向代理來解決vue項目打包后的跨域問題。
? 找到vue前端打包后所部署的nginx服務(wù)其下的配置文件nginx.conf。文章來源:http://www.zghlxwxcb.cn/news/detail-607670.html
? 如下代碼:使用當(dāng)前服務(wù)器的其他端口路徑代理8080端口下的(/api 和 /upload)文章來源地址http://www.zghlxwxcb.cn/news/detail-607670.html
server {
listen 8080;
server_name localhost;
root /usr/local/nginx/html/dist;
index index.html index.html;
location /{
root /usr/local/nginx/html/dist;
try_files $uri $uri/ /index.html;
index index.html index.html;
}
## 配置反向代理,解決跨域問題
location /api/ {
proxy_pass http://127.0.0.1:8081; ## 真實的后端接口路徑
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
location /upload/ {
proxy_pass http://127.0.0.1:8083; ## 真實的圖片請求路徑
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
到了這里,關(guān)于vue項目跨域問題(圖片跨域)devServer.proxy代理失效時,nginx反向代理解決跨域問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!