一,安裝axios
npm install axios
二,配置axios請求
1.在src目錄下新建 request 目錄
2. request 目錄下新建http.js請求
3.配置請求頭與常用請求方式封裝
1 import axios from "axios"; 2 import qs from "qs"; 3 4 // axios.defaults.baseURL = 'http://www.baidu.com/api/' //正式 5 axios.defaults.baseURL = "http://www.myapp.com/API/WebAPI/"; //測試 6 7 //post請求頭 8 axios.defaults.headers.post["Content-Type"] = 9 "application/x-www-form-urlencoded;charset=UTF-8"; 10 //設置超時 11 axios.defaults.timeout = 10000; 12 13 axios.interceptors.request.use( 14 (config) => { 15 return config; 16 }, 17 (error) => { 18 return Promise.reject(error); 19 } 20 ); 21 22 axios.interceptors.response.use( 23 (response) => { 24 if (response.status == 200) { 25 return Promise.resolve(response); 26 } else { 27 return Promise.reject(response); 28 } 29 }, 30 (error) => { 31 console.log("請求錯誤!" + error); 32 } 33 ); 34 export default { 35 //導出post請求 36 post(url, data) { 37 return new Promise((resolve, reject) => { 38 axios({ 39 method: "post", 40 url, 41 data: qs.stringify(data), 42 }) 43 .then((res) => { 44 resolve(res); 45 }) 46 .catch((err) => { 47 reject(err); 48 }); 49 }); 50 }, 51 //導出get請求 52 get(url, data) { 53 return new Promise((resolve, reject) => { 54 axios({ 55 method: "get", 56 url, 57 params: data, 58 }) 59 .then((res) => { 60 resolve(res); 61 }) 62 .catch((err) => { 63 reject(err); 64 }); 65 }); 66 }, 67 };
4.引用請求
import http from "../request/http";
http .get("GetInfoByID", { ID: "666", }) .then((res) => { console.log(res); });
4.1全局引用
修改main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import http from "./request/http";
const app = createApp(App);
app.config.globalProperties.$http = http;
app.use(store).use(router).mount("#app");
調用
const _this = this; _this.$http .get("GetColumnByid", { Cid: "5", }) .then((res) => { console.log(res); });
三.跨域問題解決(沒有跨域問題直接忽略以下)
叫后台去解決或者設置代理
vue3處理方案
在vue.config.js的module.exports里面添加
devServer: {
proxy: {
"/api": {
target: "http://www.myapp.com/API/WebAPI/",
changeOrigin: true,
pathRewrite: {
"^/api": "",
},
},
},
},
http.js里面相應的鏈接也得改改了
axios.defaults.baseURL = "/api/"; //測試
差不多就是這樣了
