首页 > 解决方案 > 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');
  }
}

标签: node.jsvue.jscorssails.js

解决方案


在您的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?


推荐阅读