原因
使用axios的時候,如果是開發(fā)環(huán)境下,WebStorm(IDEA)會自帶跨域功能,說白了就是不用考慮跨域的事情了。但是在生產(chǎn)環(huán)境下,vue前端編譯成靜態(tài)文件,只是普通的http請求,所以根據(jù)瀏覽器的跨域規(guī)則(域名、端口、協(xié)議,一個不同就是跨域),不能發(fā)送請求,所以要借助反向代理工具,比如Nginx。
例如本來的開發(fā)環(huán)境請求是這樣的:
export function getDeviceListById(code) {
let url="https://fc-mp-f8364129-599d-437d-bf25-31dc95098b4c.next.bspapp.com/user/getDeviceDataByid?id="+code;
return axios.get(url);
}
改為如下:文章來源:http://www.zghlxwxcb.cn/news/detail-726248.html
import request_app from "@/utils/requests-app";
export function getDeviceListById(code) {
let data ={"id":code}
return request_app({
url: "/user/getDeviceDataByid",
method: "get",
params: data
});
}
// @/utils/requests-app.js
import axios from "axios";
const requests_app = axios.create({
baseURL: "/app",
timeout: 10000,
// 請求頭
headers: {
"Content-Type": "application/json;charset=UTF-8",
},
});
export default requests_app;
Nginx配置如下文章來源地址http://www.zghlxwxcb.cn/news/detail-726248.html
# 反向代理
location /api/ {
proxy_pass http://localhost:8080/;
proxy_set_header x-forwarded-for $remote_addr;
}
# axios跨域處理 請求unicloud云服務(wù)空間
location /app/{
add_header 'Access-Control-Allow-Origin' '*';
proxy_set_header x-forwarded-for $remote_addr;
proxy_pass https://fc-mp-f8364129-599d-437d-bf25-31dc95098b4c.next.bspapp.com/;
}
# 配置url訪問路由,如果不配置就會導(dǎo)致跳轉(zhuǎn)的時候報404
location / {
try_files $uri $uri/ /index.html;
}
總結(jié):借助Nginx使得axios可跨域請求
到了這里,關(guān)于【vue】vue前端、生產(chǎn)(線上)環(huán)境請求unicloud云服務(wù)空間axios報錯的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!