这边有两个后端api,api的端口不同
//后端接口api
http://localhost:8386/pay/list
http://localhost:8080/app/msg
访问前端页面的路径
http://localhost:3000
在前端设置axios的基本参数
// 由于同源策略,前端不能直接调用后端接口会有跨域问题
// 跨域解决方案 1、前端配置代理 2、后端设置请求头,这边演示前端解决办法
// 我们设置axios的baseURL为前端路径,这样不会触发跨域。
const service = axios.create({
baseURL: 'http://localhost:3000',
timeout: 10000,
withCredentials: true,
})
编写调用api的请求
app.js
import request from './request'
const baseURL = '/app';
export const getMsg = () => {
return request.get(baseURL+'/msg');
}
我们调用这个方法的完整路径是
localhost:3000/app/msg
pay.js
import request from './request'
const baseURL = '/pay';
export const getList = () => {
return request.get(baseURL+'/list');
}
我们调用这个方法的完整路径是
localhost:3000/pay/list
这两个路径不能直接访问到后端接口因为是前端自己访问自己,我们需要设置代理,让请求转发到指定的后端接口api
在 vue.config中的配置
export default defineConfig({
plugins: [vue()],
server:{
port:3000,
open: true,
proxy: {
//我们前端完整路径localhost:3000/app/msg
//请求转发:如果是app开头的请求,就转发到指定的域名
//转发到的接口 http://localhost:8080/app/msg,直接访问到指定的后端api
'/app': {
target: 'http://localhost:8080/', // 后端接口的域名
changeOrigin: true,
rewrite: path => path.replace(/^\/app/, 'app'),
},
//同理,pay开头的请求路径转发到指定api
'/pay': {
target: 'http://localhost:8386/', // 后端接口的域名
changeOrigin: true,
rewrite: path => path.replace(/^\/pay/, 'pay'),
},
},
}
})
结果展示

295

被折叠的 条评论
为什么被折叠?



