一、vite使用proxy完成跨域
再vite.config.js文件中配置proxy代理,再server中有一个proxy属性可以实现我们前端代理跨域
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
open: true,
proxy: {
"/api": {
target: 'https://api-hmugo-web.itheima.net/',//跨域的地址
changeOrigin: true,//允许跨域
// rewrite: (path) => path.replace(/^\/api/, "/api")//替换我们的前缀
}
}
},
define: {
'process.env': {}
}
})
我们可以看到使用open打开服务器使用,proxy代理配置
1. 如请求的实际接口是https://api-hmugo-web.itheima.net/api/public/v1/goods/search
2、那么我们在axios的url地址就可以写为‘/api/public/v1/goods/search’
3、vite配置proxy有三种写法
proxy: {
/* 第一种写法 */
// '^/geoserver': {
// target: 'http://10.10.0.21:8080/',
// changeOrigin: true, // 允许跨域
// rewrite: (path) => path.replace(/^\/geoserver/, '/geoserver'),
// },
/* 第二种写法 */
'^/geoserver': {
target: 'http://10.10.0.21:8080/',
changeOrigin: true,
},
/* 第三种写法 */
// '/geoserver': 'http://10.10.0.21:8080/',
}
二、不使用vite中vue实现proxy代理跨域
与vite中vue实现思路大致相似
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
open: true,
proxy: {
"/api": {
target: 'https://api-hmugo-web.itheima.net',//跨域的地址
changeOrigin: true, // 允许跨域
// pathRewrite: {
// '^/api': '' // 标识替换,使用 '/api' 代替真实的接口地址
// }
}
}
}
})
// 使用 '/api' 代替真实接口地址
// 真实地址为 http://localhost:3000/users/find
// this.$axios.get('/api/users/find').then(res => {
// console.log(res)
// })
同样实在vue.config.js文件中进行配置代理
使用:
import axios from 'axios'
import { onMounted } from 'vue';
let getList = async () => {
let { data } = await axios.get('/api/public/v1/goods/search')
console.log(data.message.goods);
}
onMounted(() => {
getList()
})
通过axios直接进行使用
三、react配置代理
1、可以在package.json下配置跨域 追加如下配置
{
"xxx": {},
......
"proxy":"https://www.xxxxxxx/"
}
该方法缺点很明显不能配置多个代理
2、src目录下创建setupProxy.js文件使用插件http-proxy-middleware配置代理
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use('/api', createProxyMiddleware({
target: 'https://api-hmugo-web.itheima.net',//后台服务器地址
changeOrigin: true,
// pathRewrite: {
// '^/api': '',
// },
}))
};
通过创建中间件来进行配置。