1.創(chuàng)建vue項(xiàng)目
vue create demo
demo是項(xiàng)目名稱(chēng)
2.安裝axios?
進(jìn)入demo里面打開(kāi)終端(黑窗口),執(zhí)行
npm install axios
3.進(jìn)行config.js配置
devServer: { host: "0.0.0.0", // 是否可以被覆蓋 port: 8090, // 配置本地端口號(hào) open: true, //解決跨域問(wèn)題 proxy: { // 正式 "/api": { target: "http://IP地址:端口號(hào)/", changeOrigin: true, secure: false, // 如果是https接口,需要配置這個(gè)參數(shù) pathRewrite: { "^/api": "", }, }, }, }, },
4.main.js里引入
//http封裝請(qǐng)求 import axios from "axios"; axios.defaults.baseURL = "/api"; axios.defaults.headers = //公共攜帶請(qǐng)求頭 //大部分是 "Content-Type:application/json;charset=UTF-8" axios.defaults.withCredentials = true;
5.src目錄下新建Utils文件夾,在內(nèi)封裝request.js
import axios from "axios";//引入axios const request = axios.create({//進(jìn)一步封裝axios baseURL: "/api",//配置跟路由 timeout: 5000,//配置請(qǐng)求超時(shí)時(shí)間 }); //添加請(qǐng)求攔截器 request.interceptors.request.use(function (config) {} //添加響應(yīng)攔截器 request.interceptors.request.use((res) => { return res; }), (err) => { return Promise.reject(err); }; export default request; //暴露出去
6.以login路由為示例? src文件下新建api文件,在api內(nèi)新建login.js
import request from "@/utils/request"; // 引入request // 登錄 export const UserLogin = (params) => {//封裝login請(qǐng)求 return request({ url: "/login",//請(qǐng)求地址 method: "post",//請(qǐng)求方式 data: params,//請(qǐng)求體 }); };
7.在頁(yè)面內(nèi)引入方法,并使用
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-426970.html
簡(jiǎn)單明了文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-426970.html
到了這里,關(guān)于Vue項(xiàng)目的網(wǎng)絡(luò)請(qǐng)求代理到封裝詳細(xì)步驟的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!