報錯
Access to XMLHttpRequest at '<http://localhost:3000/player>' from origin '<http://localhost:4000/>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解決
vue需要配置自定義代理規(guī)則進行跨域訪問
配置跨域
官方文檔:https://cn.vitejs.dev/config/server-options.html#server-proxy
在vite.config.ts修改:
//vite.config.ts
export default defineConfig({
//......
server: {
//......
port: 4000, //vite的默認端口(別和后端沖突了)
proxy: {
"/api": { //代理的請求
target: "http://localhost:8000", //后端的地址
changeOrigin: true, //開啟跨域訪問
rewrite: (path) => path.replace(/^\/api/,''), //重寫前綴(如果后端本身就有api這個通用前綴,那么就不用重寫)
},
},
},
})
發(fā)起請求的地方:文章來源:http://www.zghlxwxcb.cn/news/detail-760488.html
axios.defaults.baseURL ='/api'; //配置前綴
axios.get('info') //這里會發(fā)送到http://localhost:4000/info
生產(chǎn)環(huán)境配置跨域
生產(chǎn)環(huán)境配置跨域,還需要編輯nginx的配置文件,在server
對象中再添加一個location
對象(別忘了上一個對象末尾的分號;
)文章來源地址http://www.zghlxwxcb.cn/news/detail-760488.html
server {
//......
location /api/ {
proxy_pass http://localhost:8000/; //后端的地址
}
}
到了這里,關(guān)于解決vite的跨域問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!