在該專案的vscode命令列下載
npm i axios

在使用axios時涉及跨域問題
你的8080視窗雖然發了請求,服務器也回傳了訊息,但是你收不到
1.cors 方式-----服務器給你回傳回應時加特殊的回應頭
2.jsonp方式 借助了 script 標簽里面的src屬性 引入外部資源時,不受同源策略限制辦到的 只能解決get請求的跨域問題
3.代理服務器方式

4.利用vue-cli腳手架解決跨域問題
方式一
這種方式不能設定多個代理,只能配置一個代理,而且不能靈活控制要不要走代理
在vue.config.js里面進行全域配置,寫好埠號就行了,不用寫具體路徑了
//開啟代理服務器 devServer: { proxy:'http://localhost:5000' } App.vue中 發起get請求時直接填8080視窗 <template> <div> <button @click="getStudents">捕獲</button> </div> </template><script> import axios from "axios"; export default { name: "App", methods: { getStudents() { //http://localhost:8080/students這里代表著代理服務器的地址加上具體路徑訪問資料 axios.get("http://localhost:8080/students").then( (response) => { console.log("請求成功", response.data); }, (error) => { console.log("請求失敗", error.message); } ); }, }, }; </script> 如果在public里面有students,那么就不用走代理,直接拿資源
而不是去服務端的 students路徑取值
方式二:
vue.config.js:
devServer: { proxy: { '/atguigu': { target: 'http://localhost:5000', } } } App.vue: axios.get("http://localhost:8080/atguigu/students").then( (response) => { console.log("請求成功", response.data); }, (error) => { console.log("請求失敗", error.message); } );
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, lintOnSave: false, //方式二 devServer: { proxy: { '/atguigu': { target: 'http://localhost:5000', pathRewrite: {'^/atguigu': ''} //將匹配所有以atguigu開頭的路徑,將atguigu變成空字串 ws:true,//websocket用于支持websocket changeOrigin:false//說謊是否來自原客戶端埠號 } } } }) 5.vue-resource vue插件庫 下載 npm i vue-resource 使用只要把axios替換成this.$http.get()就行了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/549081.html
標籤:其他
