首页 > 解决方案 > 使用 Vue 从 localhost 调用端点时出现 Cors 错误

问题描述

我正在使用 Vue 创建一个简单的应用程序,并使用 axios 调用端点

axios.post(url, {
  email: this.email,
})
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

我得到错误

来自原点“http://localhost:8080”的 CORS 策略已阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

问题不在服务器级别,我已经从 Postman 或直接使用 CURL 进行了测试,它不会产生错误。


解决方案

感谢 Shrinivas Bendkhale 的评论。我设法解决了这个问题。

起初它不起作用,因此有必要将“logLevel”和“pathRewrite”选项添加到代理。

// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      '^/rp': {
        target: process.env.API_OLD_SERVER,
        secure: false,
        logLevel: 'debug',
        pathRewrite: { 
          '^/rp': '/'
        }
      },
    },
  },
}

所以我的电话如下

axios.post('/rp/full-path', {
    usermail: this.email,
  })
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error);
    });

标签: vue.jsvuejs2axios

解决方案


在 vue.config.js 文件中添加以下行:

    // vue.config.js
    module.exports = {
    // options...
         devServer: {
            proxy: 'https://mywebsite/',
         }
    }

推荐阅读