vue.js - 使用 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”选项添加到代理。
- 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.config.js 文件中添加以下行:
// vue.config.js
module.exports = {
// options...
devServer: {
proxy: 'https://mywebsite/',
}
}
推荐阅读
- entity-framework-core - EF Core Tool 忽略 .net core 2.1 和 3.1 中的 launchSettings.json
- python - 在 Python 中初始化基类中的公共属性
- c++ - 如果 C++ 程序发生错误,如何删除动态分配的对象?
- amazon-web-services - 配置 AWS Lambda 函数以使用最新版本的层
- android - 当 kotlin 协程启动并且应用程序突然移动到后台并变得空闲时会发生什么?
- mysql - 为什么使用空白密码的 MySQL root 不能在 shell 脚本中工作?
- r - R中的转置和合并列
- python - 导入db时不存在SQLAlchemy关系
- vba - Vba 抓取 img alt src
- react-native - 无法让 React-Native-WebRTC 工作