node.js - VueJS 前端和 SailsJS 后端之间的 Axios CORS 问题
问题描述
我已经把厨房水槽扔到了这个问题上,但我仍然无法从我的 VueJs 前端到我的 SailsJS 后端建立 Axios 连接。Vue 正在运行localhost:8080
,Sails 正在运行localhost:1337
。这是错误消息和一些相关设置 -
Vue - vue.config.js
module.exports = {
devServer: {
proxy: {
'/': {
target: 'http://localhost:1337',
changeOrigin: true,
pathRewrite: {
'^/': ''
}
}
}
}
}
Vue - src/views/Example.vue
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.crossDomain = true
axios.defaults.headers['Access-Control-Allow-Origin'] = '*'
const response = await axios.get('http://localhost:1337/hello')
帆 - config/security.js
module.exports.security = {
cors: {
allRoutes: true,
allowOrigins: '*',
allowCredentials: false,
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
headers: 'content-type',
allowAnyOriginWithCredentialsUnsafe: true,
}
};
帆 - api/controllers/ExampleController.js
module.exports = {
hello: function(req, res) {
return res.status(200).send('hello');
}
}
我已经根据其他 SO 建议对这些设置进行了大量修改,但似乎没有解决这个 CORS 错误。有任何想法吗?
编辑
我找到了一种可行的解决方案,尽管并不理想。如果我在操作级别添加它,它将发送我的前端将接受的响应。
帆 - api/controllers/ExampleController.js
module.exports = {
hello: function(req, res) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
return res.status(200).send('hello');
}
}
解决方案
在您的sails config/routes.js 中,尝试:
'POST /api/v1/your_route': { action: 'your_path_to_action', cors: false, csrf: false },
为什么你的 axios 默认axios.defaults.baseURL = 'http://localhost:8080'
设置为:8080?
推荐阅读
- annotations - 函数的 Modelica 注释逆被忽略
- docker - 没有互联网的 Docker
- excel - 将工作表复制为新文件,所有单元格都为数字而不是公式
- amazon-web-services - 为什么 AWS 状态机不会将执行显示为“超时”,而是显示为“失败”?
- python - 刽子手游戏(Python)
- node.js - 为什么我保存 ObjectId('key'),而不是 mongodb 中的值?
- sql-server - 即使数据没有更新,MERGE 语句也会更新
- mfc - 在 MFC 应用程序中调整大小的 PNG 图像的显示问题
- c++ - 定期清理地图
- kubernetes-helm - 在 k8s 集群中通过入口公开服务时找不到 404 页面