一、配置axios请求响应拦截
在src/utils/request.js
import axios from "axios";
//拦截器(请求,响应)
//响应
axios.interceptors.response.use(res => {
//成功
return res.data;
}, err => {
//失败
return Promise.reject(err)
})
//请求
axios.interceptors.request.use(config=>{
//配置基础url,以后所有请求地址自动携带api
config.baseURL = '/api';
return config;
})
export default axios;
二、在 vue.config.js 文件设置代理请求
const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, //忽略lint检测
//请求代理
devServer: {
proxy: {
//http://localhost:7001/api/name -> http://39.102.89.187:7001/name
'^/api': {
target: 'http://39.102.89.187:7001',
pathRewrite: {
'/api': ''
}
},
}
}
});
三、在 src/api/index.js 中设置请求地址
import axios from "@/utils/request";
/**
* 获取 banner 数据
* @returns
*/
export async function getBanner() {
return await axios.get('/banner');
}
/**
* 获取菜单
* @param {object} [params] -> 对象
* @param {string} [params.userId] -> 用户id
* @param {string} [params.classify] -> 菜谱分类
* @param {string} [params.craft] -> 工艺
* @param {string} [params.flavor] -> 口味
* @param {string} [params.hard] -> 难度
* @param {string} [params.people] -> 人数
* @param {string} [params.page] -> 页码
* @returns
*/
export async function getMenuQuery(params) {
return await axios.get('/menu/query', { params });
}
四、调用api
import { getBanner, getMenuQuery } from "@/api/index";
await getBanner();
await getMenuQuery();
getBanner().then(res=>{
})
getMenuQuery().then(res=>{
})
标签:axios,return,string,vue,配置,param,api,params From: https://www.cnblogs.com/Lmyong/p/16924738.html