【发布时间】:2023-03-26 15:44:02
【问题描述】:
我正在为个人网站设置休息 api。我的个人站点是用 Vue.js 构建的,api 服务器是用 express 构建的。我在服务器上尝试了几种不同的 CORS 配置,但我似乎仍然收到飞行前错误,所以我认为我在某处缺乏理解。
我最初的目标是通过容器化 api/auth 服务器并将其与前端 vue.js 应用程序分开托管来了解 docker。这是问题的一部分还是不好的做法?
以下是我尝试过的两个 CORS 配置,我在其他帖子中找到了但没有成功。
配置#1:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://0.0.0.0:5000"); // I tried setting a specific IP as well as the * wildcard
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Custom-Header");
// I think this if statement should respond the preflight request.
if (req.method === "OPTIONS") {
return res.status(200).end();
}
return next()
})
配置#2:
const whitelist = [
'http://0.0.0.0:5000',
];
const corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
},
credentials: true
};
app.use(cors(corsOptions));
我也想知道这是否与我提出请求的方式有关,所以我添加了从 Vue.js 应用程序使用的方法:
attemptLogin: function(event) {
event.preventDefault()
axios.post('http://0.0.0.0:5000/auth/login', {
username: this.username,
password: this.password
})
.then(res => {
if (res.data.success) {
this.updateLoginStatus()
this.updateJwt(res.data.token)
}
})
.catch(error => {
console.log(error)
});
}
其他可能有用的信息:
我尝试在同一台计算机上同时运行前端和后端,但没有成功。现在我在笔记本电脑上运行后端,在台式机上运行前端。
如果您需要更多上下文,这里是两个存储库的 GitHub 存储库:
【问题讨论】:
-
浏览器在 devtools 控制台中记录的确切错误消息是什么?响应的 HTTP 状态代码是什么?
-
当您使用 curl 或 Postman 或其他工具向
http://10.10.81.100:5000/auth/login发送 OPTIONS 请求时,您会返回哪些状态码和标头?例如,使用 curl,curl -i -X OPTIONS -H "Origin: http://localhost:8080" http://10.10.81.100:5000/auth/login -
Postman 不需要进行预飞行,因此不会失败。仅浏览器即可预检选项请求。
标签: node.js express vue.js cors preflight