vben admin中后台开启cors,前端还是存在跨域问题,怎么解决
如果在 Vue Vben Admin 中后台已经开启了 CORS,但前端仍然存在跨域问题,可以尝试以下几种解决方法:
在 Vue CLI 中使用代理:
在 Vue CLI 的配置文件 vue.config.js
中添加代理配置,将前端请求代理到后台 API 服务器。示例代码如下:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://backend-api-server',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
这样,前端发送的请求会被代理到 http://backend-api-server/api
,跨域问题就会被解决。
在后台添加允许的源头:
确保后台的 CORS 配置中添加了前端的域名,例如:
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'http://frontend-domain');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
});
// ...其他中间件和路由配置
app.listen(8080, () => {
console.log('Server is running on port 8080');
});
这样,在后台中添加了前端的域名到允许的源头后,前端就能够发送跨域请求了。
使用 CORS 跨域库:
在 Vue Vben Admin 中,可以使用 cors
库来解决跨域问题。首先,安装 cors
库:
npm install cors
然后,在后台代码中添加以下代码:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
// ...其他中间件和路由配置
app.listen(8080, () => {
console.log('Server is running on port 8080');
});
这样,cors
库会自动处理跨域请求,前端就可以正常发送跨域请求了。
请根据实际情况选择适合的解决方案,并根据代码示例进行配置。如果遇到任何问题,请提供更多的错误信息或代码,以便我们更好地帮助您解决问题。
export default defineApplicationConfig({
overrides: {
base: VITE_PUBLIC_PATH,
optimizeDeps: {
include: [
'echarts/core',
'echarts/charts',
'echarts/components',
'echarts/renderers',
'qrcode',
'@iconify/iconify',
'ant-design-vue/es/locale/zh_CN',
'ant-design-vue/es/locale/en_US',
],
},
server: {
https: false,
proxy: {
'/basic-api': {
target: '接口域名',
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(new RegExp(`^/basic-api`), ''),
// only https
// secure: false
},
'/upload': {
target: 'http://localhost:3300/upload',
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(new RegExp(`^/upload`), ''),
},
},
},
},
});
现在的情况是本地可以代理成功,但是部署生产环境就爆404了