我正在尝试使用vuejs在前面设置一个简单的注册/登录表单,并使用护照库通过Express js在服务器上安装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未设置为我的实际值。
答案 0 :(得分:0)
在chrome浏览器的最新更新之后,我也开始出现此错误。解决此问题的解决方案转到chrome:// flags并默认禁用 SameSite cookie ,并禁用启用删除SameSite = None cookie 。这样可以解决您的问题。我想在创建会话时解决此更改Cookie设置(相同站点属性)的另一种方法。
答案 1 :(得分:0)
找到解决方案,谢谢@skirtle。我将axios.defaults.baseURL设置为“ http://127.0.0.1:3000/api/”,但是localhost和127.0.0.1不可互换,并且被认为是两个不同的域。我切换到axios.defaults.baseURL =“ http:// localhost:3000 / api”,它解决了该问题。