You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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() and res.send() separately, we create an object containing both user and token, then send it once with res.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 id and email instead of the full user object. It's best practice to keep JWT payloads small and avoid sensitive data (even if your users table 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:34:15