// 解决 Vue 中 CORS 错误的示例代码
// 在后端服务器中,确保响应头包含正确的 CORS 配置。
// 例如,在 Express.js 中可以这样做:
const express = require('express');
const cors = require('cors');
const app = express();
// 使用 cors 中间件
app.use(cors());
// 或者指定允许的域名
app.use(cors({
origin: 'http://your-vue-app-domain.com'
}));
app.get('/api/data', (req, res) => {
res.json({ message: 'This is CORS-enabled for a Single Origin.' });
});
app.listen(5000, () => {
console.log('Server is running on port 5000');
});
// 在 Vue 应用中,确保你正确配置了代理来避免 CORS 问题。
// 例如,在 vue.config.js 中添加如下配置:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
};
// 这样,当你在 Vue 应用中发起请求时,可以使用相对路径:
axios.get('/api/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
// 通过以上配置,Vue 应用可以通过代理服务器转发请求到后端 API,从而避免 CORS 问题。
cors
中间件来允许跨域请求。你可以全局启用 CORS,或者指定特定的域名。vue.config.js
配置开发服务器的代理,将 /api
路径下的请求转发到后端服务器,从而避免浏览器中的 CORS 限制。axios
发起请求时,可以使用相对路径 /api/data
,实际请求会被代理到后端服务器。这样配置后,Vue 应用和后端服务器之间的通信就不会受到 CORS 限制的影响。
上一篇:vue sm4加密
下一篇:vue $listeners
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站