跨域問題
跨域請求數(shù)據(jù),
瀏覽器
同源策略的保護(hù)機(jī)制, 通過proxy
實(shí)現(xiàn)跨域請求數(shù)據(jù); 如果直接postman
請求是不會報錯的,vue3
報錯是因?yàn)榻?jīng)過瀏覽器了, 數(shù)據(jù)其實(shí)返回了, 但是別瀏覽器的同源策略屏蔽了。
問題
本地調(diào)試, 后端使用**
http://localhost:8081
作為接口地址, 報錯[vite] http proxy error
**
問題分析
可能是localhost
被使用了。 Node.js
在 v17
以下版本中會對DNS
解析地址的結(jié)果進(jìn)行重新排序。 當(dāng)訪問localhost
時, 瀏覽器使用DNS
來解析地址, 這個地址可能與Vite
正在監(jiān)聽的地址不同。當(dāng)?shù)刂凡灰恢聲r。導(dǎo)致接口報錯。
解決方案
后端不要使用
localhost
作為接口域名
,配置一個虛擬域名
或者使用127.0.0.1
vite.config.js
中配置代理, 解決跨域問題。
后端接口如果有統(tǒng)一的標(biāo)識, 比如api
的配置
vite.config.js
文章來源:http://www.zghlxwxcb.cn/news/detail-713230.html
export default defineConfig({
server: { // 中轉(zhuǎn)服務(wù)器
proxy: { // 通過代理實(shí)現(xiàn)跨域,搭理這個地址http://localhost:8081
'/api': { // 路徑, 作為就是替換域名
target: 'http://127.0.0.1:8081', // 表示要替換的服務(wù)端地址
changeOrigin: true, // 表示開啟代理, 允許跨域請求數(shù)據(jù)
secure: false, // 如果是https接口,需要配置這個參數(shù)
}
}
}
})
釋義
: 如果前端請求帶有/api
的接口地址, 都會轉(zhuǎn)發(fā)到http://127.0.0.1:8081
這個服務(wù)端地址上面。模板中請求示例
<template>
<div>{{ store.state.msg }}</div>
<p><button @click="updateMsg()">改變數(shù)據(jù)</button></p>
</template>
<script>
export default{
inject:['store'],
/**
* fetch 原生js, 不是ajax的封裝,是一種http數(shù)據(jù)請求的方式,es6中的語法
*/
mounted(){
/**
* fetch 返回promise對象
*
* 跨域請求數(shù)據(jù), 瀏覽器同源策略的保護(hù)機(jī)制, 通過proxy實(shí)現(xiàn)跨域請求數(shù)據(jù)
*/
let url = '/api/tests' // 模板中直接寫相對路徑就可以
fetch(url).then((res)=>{
console.log(res.json())
})
},
methods:{
updateMsg:function(){
this.store.updateMsg()
}
}
}
</script>
(*)后端接口如果沒有統(tǒng)一的標(biāo)識,自己定義一個, 然后重寫再去掉
這樣配置, 通用性更高一些。
vite.config.js
export default defineConfig({
server: { // 中轉(zhuǎn)服務(wù)器
proxy: { // 通過代理實(shí)現(xiàn)跨域,搭理這個地址http://localhost:8081
'/path': { // 路徑, 作為就是替換域名
target: 'http://127.0.0.1:8081', // 表示要替換的服務(wù)端地址
changeOrigin: true, // 表示開啟代理, 允許跨域請求數(shù)據(jù)
secure: false, // 如果是https接口,需要配置這個參數(shù)
rewrite: path => path.replace(/^\/path/, '') // 設(shè)置重寫路徑, 去掉path
}
}
}
})
模板中請求示例
文章來源地址http://www.zghlxwxcb.cn/news/detail-713230.html
<template>
<div>{{ store.state.msg }}</div>
<p><button @click="updateMsg()">改變數(shù)據(jù)</button></p>
</template>
<script>
export default{
inject:['store'],
/**
* fetch 原生js, 不是ajax的封裝,是一種http數(shù)據(jù)請求的方式,es6中的語法
*
* axios 也是http數(shù)據(jù)請求的方式, 但它是第三方庫, 需要引入、安裝
*/
mounted(){
/**
* fetch 返回promise對象
* 特別注意, 接口路徑多了一個path, 代理轉(zhuǎn)發(fā)的時候, 會去掉的。
*/
let url = '/path/api/tests'
fetch(url).then((res)=>{
console.log(res.json())
})
},
methods:{
updateMsg:function(){
this.store.updateMsg()
}
}
}
</script>
到了這里,關(guān)于vue3配置代理--[vite] http proxy error的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!