【发布时间】:2020-12-16 18:25:26
【问题描述】:
我正在尝试设置一个简单的注册/登录表单,前面带有 vuejs,并使用护照库设置带有 express js 的服务器来设置本地和社交媒体启动。 但是当我使用本地策略登录时,我似乎无法将 cookie 传递到前端。 此外,当我使用 google 登录时,我会在前端获得 cookie,但它不会随下一个 API 调用发送,但这是另一个问题的主题。
我对此感到困惑,所以我做了一个简单的项目来接收和发送 cookie,它可以工作。这是后端:
//headers in app.js
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// index file
router.get('/cookie', function (req, res, next) {
res.cookie("token", "mytoken");
res.send("cookie sent");
});
router.get('/info', function (req, res, next) {
cookies = req.cookies;
console.log(cookies);
res.cookie("token", "mytoken");
res.send("cookie sent");
});
这是我调用 API 的前端方法:
methods: {
async getCookie() {
await axios.get("http://localhost:3000/cookie",{withCredentials:true}).then((response) => {
console.log(response);
}).catch((e) => {
console.log(e);
});
},
async sendCookie() {
await axios.get("http://localhost:3000/info",{withCredentials:true}).then((response) => {
console.log(response);
}).catch((e) => {
console.log(e);
});
}
}
这样我在请求中传递cookie并接收它没有问题。
现在在我的实际项目中,我在后端有这个
//Headers just like the other project
router.post('/users/login', function (req, res, next) {
passport.authenticate('local', { session: false }, function (err, user, info) {
if (err) { return next(err); }
if (user) {
res.cookie('token', 'mytoken');
return res.json({ user: user.toAuthJSON() });
} else {
return res.status(401).json(info);
}
})(req, res, next);
});
前端调用:
// Service file to call the api
axios.defaults.baseURL = "http://127.0.0.1:3000/api/";
axios.defaults.withCredentials = true;
const ApiService = {
get(resource, slug = "") {
return axios.get(`${resource}/${slug}`).catch(error => {
throw new Error(`ApiService ${error}`);
});
},
...
}
export default ApiService;
//actual call in authetification module file
[LOGIN](context, credentials) {
return new Promise(resolve => {
ApiService.post("users/login", { email: credentials.email, password: credentials.password })
.then(({ data }) => {
context.commit(SET_AUTH, data.user);
resolve(data);
})
.catch(({ response }) => {
context.commit(SET_ERROR, response.data.errors);
});
});
},
//
我看不出我的两个项目有什么不同会在 Chrome 上触发最后一个警告。
编辑:在我原来的帖子中 axios.defaults.baseURL 没有设置为我的实际值。
【问题讨论】:
-
你在这两种情况下都使用
localhost:8080和localhost:3000吗?看来您来自代码,但如果是这种情况,cookie 域将匹配并且错误消息似乎暗示它们不匹配。 -
你是对的。我对我的代码进行了一些更改,以使问题更简洁。 axios.defaults.baseURL 的值位于使用 127.0.0.1 而不是 localhost 的配置文件中。这就是问题所在。显然 localhost 和 127.0.0.1 是不可互换的。
标签: express google-chrome vue.js cookies