英文:
Session not persisting on my website with express-session - what am I doing wrong?
问题
以下是您要翻译的代码部分:
我试图在用户登录后初始化网站会话,但出于某种原因,一旦用户成功登录,就不会将Cookie发送到浏览器,也不会保持会话。当我尝试在Postman中使用网站的API时,会话得以成功保持,但在Google浏览器中则不会。
这是我用于初始化会话的代码:
const express = require('express');
const app = express();
const dotenv = require('dotenv').config();
const session = require('express-session');
const store = session.MemoryStore();
const helmet = require('helmet');
const cors = require('cors');
const cookieParser = require('cookie-parser');
app.enable("trust proxy");
app.use(cookieParser());
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
resave: false,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
cookie: {maxAge: 10006060, sameSite: 'none', secure: false},
store,
}));
一旦用户成功登录,会将'用户'属性和'已验证'属性附加到会话对象,并对任何后续请求进行身份验证,服务器将使用以下函数检查客户端是否经过身份验证:
const checkIfAuthenticated = (req, res, next) => {
if(req.session.authenticated){
next();
} else {
res.json("请进行身份验证!");
};
};
用户成功登录后,应该成功保持会话。实际发生的情况是,一旦用户成功登录并尝试访问和修改个人数据,他们将收到"请进行身份验证!"的消息,这意味着没有初始化会话。
这是我的前端登录代码(需要用户名和密码):
export async function loginUser(username, password){
console.log(username, password);
const res = await fetch('http://localhost:4001/login', {
method: 'POST',
body: JSON.stringify({username, password}),
headers: {
"Content-Type": "application/json",
},
});
const jsonRes = await res.json();
return jsonRes;
}
这是我用于获取产品数据的前端代码(任何对产品数据的请求都首先由上面编写的'checkIfAuthenticated'函数进行身份验证,如果用户经过身份验证,服务器将发送产品,否则用户将被要求进行身份验证):
export async function getAllProducts(){
const products = await fetch('http://localhost:4001/products');
const jsonProducts = await products.json();
return jsonProducts;
}
我应该在代码中进行哪些更改以使其正常工作?
英文:
I'm trying to initialize a session in my website once a user logs in, but for some reason, once a user successfully logs in, a cookie isn't sent to the browser and a session isn't maintained. When I tried playing with the website's API in Postman, a session was successfully maintained, but in Google browser it isn't.
This is my code for initializing a session:
const express = require('express');
const app = express();
const dotenv = require('dotenv').config();
const session = require('express-session');
const store = session.MemoryStore();
const helmet = require('helmet');
const cors = require('cors');
const cookieParser = require('cookie-parser');
app.enable("trust proxy");
app.use(cookieParser());
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
resave: false,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
cookie: {maxAge: 1000*60*60, sameSite: 'none', secure: false},
store,
}));
Once a user successfully logs in, a 'user' property and an 'authenticated' property get attached to the session object, and for any subsequent request, the server checks if the client is authenticated with the following function:
const checkIfAuthenticated = (req, res, next) => {
if(req.session.authenticated){
next();
} else {
res.json("Please authenticate yourself!");
};
};
After a user successfully logs in , a session should successfully be maintained. What actually happens is that once a user logs in successfully and tries to access and modify personal data, they are sent "Please authenticate yourself!", meaning that no session was initialized.
This is my frontend code for logging in (a username and a password re needed):
export async function loginUser(username, password){
console.log(username, password);
const res = await fetch('http://localhost:4001/login', {
method: 'POST',
body: JSON.stringify({username, password}),
headers: {
"Content-Type": "application/json",
},
});
const jsonRes = await res.json();
return jsonRes;
}
And this is my frontend code for fetching products data (Any request to the products data is first authenticated by the 'checkIfAuthenticated' function written above, and if the user is authenticated, the server sends the products, and if not, the user will be asked to authenticate themself):
export async function getAllProducts(){
const products = await fetch('http://localhost:4001/products');
const jsonProducts = await products.json();
return jsonProducts;
}
What should I change in my code in order for it to work properly?
答案1
得分: 1
以下是您要翻译的内容:
fetch('http://localhost:4001/login')
跨域的Ajax请求不支持存储并由浏览器自动发送的凭据(例如Cookies),除非您明确设置了credentials选项并且在服务器的CORS响应中允许它。
fetch('http://localhost:4001/login', {
method: 'POST',
credentials: 'include'
});
以及
fetch('http://localhost:4001/products', { credentials: 'include' });
以及
app.use(cors({ credentials: true }));
英文:
> fetch('http://localhost:4001/login'
Cross-origin Ajax requests do not support credentials that are stored and automatically sent by the browser (such as cookies) unless you explicitly set the credentials
option and allow it in the CORS response from the server.
fetch('http://localhost:4001/login', {
method: 'POST',
credentials: 'include'
and
fetch('http://localhost:4001/products', { credentials: 'include' });
and
app.use(cors({ credentials: true }));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论