我的cookie正在从后端传递到前端,并且它也可以在控制台上的headers选项卡中的Set-Cookie中使用,但是这样一来,cookie就不会出现在应用程序选项卡中的前端,这会在每次重新加载时将我注销。
这是我在后端的代码:我的App.js
const express = require("express");
const app = express();
const cookieParser = require("cookie-parser")
const bodyParser = require("body-parser")
const cloudinary = require("cloudinary")
const fileupload = require("express-fileupload");
const cors = require('cors')
const errorMiddleWares = require("./middleWares/errors")
// app.use(cors({ origin: "http://localhost:3000", credentials: true }));
const corsOptions = {
origin: true,
credentials: true,
};
app.use(cors(corsOptions));
and in my sendToken module for the cookies:
const sendToken = (user, statusCode, res) => {
// the user will be the userschema attached in the authusercontrolllers, also the status code too, but the res is from here
//create jwt token
const token = user.getJwtToken();
//to store jwt token in the cookie, we prepare options
const options = {
expires: new Date(
Date.now() + process.env.COOKIE_EXPIRES_TIME * 24 * 60 * 60 * 1000
),
httpOnly: true,
sameSite:"None",
secure:true
}
res.setHeader('Set-Cookie', `token=${token}`);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.status(statusCode).cookie("token", token, options).json({
success: true,
token,
user
})
};
1条答案
按热度按时间1u4esq0p1#
在development/http中,使用
secure: false
。安全的true
可以防止在http通信中设置cookie。我还建议为本地开发设置一个
dotenv
(.env
)配置,然后执行类似secure: process.env.INSECURE_COOKIES !== "true"
然后在你的envfile(通常是
.env
)中INSECURE_COOKIES=true