Node.js登录接口如何同时返回用户信息与JWT令牌?
How to Return User Info + JWT Token Together in Node.js Login Endpoint
Hey there! I see the issue here—your current code is trying to send two separate responses (res.json(user[0]) followed by res.send({ token })), which won't work in Express because you can only send one HTTP response per request. Let's fix this by bundling both the user data and JWT token into a single response object.
Here's the corrected handleSignin function:
const handleSignin = (req, res, db, bcrypt, jwt) => { const { email, password } = req.body; if (!email || !password) { return res.status(400).json('Incorrect form submission'); } db.select('email', 'hash').from('login') .where('email', '=', email) .then(data => { const isValid = bcrypt.compareSync(password, data[0].hash); if (isValid) { return db.select('*').from('users') .where('email', '=', email) .then(user => { // Sign the token with minimal user data (best practice!) jwt.sign( { id: user[0].id, email: user[0].email }, // Only include necessary fields 'secretkey', { expiresIn: '1000s' }, (err, token) => { if (err) return res.status(500).json('Failed to generate token'); // Send both user info and token in one response res.json({ user: user[0], token: token }); } ); }) .catch(err => res.status(400).json('unable to get user')); } else { res.status(400).json('wrong credentials'); } }) .catch(err => res.status(400).json('wrong credentials')); }; module.exports = { handleSignin };
Key Changes Explained:
- Single Response: Instead of calling
res.json()andres.send()separately, we create an object containing bothuserandtoken, then send it once withres.json(). This avoids the common "Cannot set headers after they are sent to the client" error. - Optimized JWT Payload: I updated the payload to only include
idandemailinstead of the full user object. It's best practice to keep JWT payloads small and avoid sensitive data (even if youruserstable doesn't return sensitive fields now, this is a safe habit to build). - Token Generation Error Handling: Added a check for errors when signing the token, so you can return a proper 500 status if something goes wrong with JWT creation.
How It Works:
After validating credentials and fetching user data, we generate the JWT token, then send both the user details and token to your React frontend in one JSON response. Your frontend can then store the token (usually in localStorage or a secure cookie) and use it for authenticated requests later.
内容的提问来源于stack exchange,提问作者JKhan
相关产品推荐
相关产品推荐

