首先,在vue專案中安裝axios
npm install axios --save
全域引入時用
import axios from 'axios'
Vue.use(VueAxios,axios);
axios的get請求
getdata(){
this.axios.get('xxxxx(url)')
.then((response)=>{
console.log(response.data)
})
.catch((response)=>{
console.log(response)
})
}
axios直接進行訪問會出現跨域問題,需要配置代理了,(前提是服務器沒有設定禁止跨域的權限問題)
- config檔案夾下的index.js檔案中配置 (如果沒有該檔案就直接配置生成該檔案放到專案最外層生成vue.config.js)
module.exports = {
// devServer 配置本地服務器
devServer: {
open:true,//自動打開瀏覽器
// port: 8080,//自定義埠
// 代理地址
proxy: {
'/api-search': {
target:"https://m.kongfz.com", // 真正需要請求的地址
changeOrigin: true, // 是否跨域(修改請求源)
},
}
},
}
// https://m.kongfz.com/api-search/product/home/mobile?bizType=wap&host=msearch
- 配置好進行get請求
getData() {
axios({
method:"get",
url:"/api-search/product/home/mobile?bizType=wap&host=msearch",
headers: {"Content-Type": "application/json; charset=utf-8"}
})
.then(res => {
console.log('資料是:', res);
})
.catch(err => {
console.log('獲取資料失敗', err);
});
}
這樣get請求就會跨域獲取到資料了
!!! 記得配置修改完專案要重啟
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/4438.html
標籤:其他
