我正在为个人站点设置rest 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 Repos:
答案 0 :(得分:0)
如果您从同一来源运行,那应该没问题。我怀疑您是通过npm run serve运行Vue应用程序,然后将其指向在另一台服务器上运行的后端服务器。
尝试在后端创建名为public的目录。在Vue中,运行npm run build
,然后获取缩小的文件并将其放置在公共目录中。
然后使用express在节点中授予访问权限:
app.use(express.static(path.join(__dirname, 'public')));
答案 1 :(得分:0)
问题可能是,而不是
axios.post('http://0.0.0.0:5000/auth/login', {
username: this.username,
password: this.password
})
尝试using http://0.0.0.0:5000/auth/login/
如果末尾没有大刀阔斧的话,我以前在mozilla和其他浏览器上也会遇到预检错误。我可以知道您遇到的确切CORS错误是什么?