NodeJS 在后端获取未定义的令牌

4xy9mtcn  于 2023-05-06  发布在  Node.js
关注(0)|答案(2)|浏览(154)

你好,我试图在我的应用程序中使用我的令牌后,用户登录,但在我的控制台得到一个未定义的响应。下面是我的代码。我如何纠正我的代码,以便能够访问应用程序内的令牌,并使用它来执行应用程序的其他功能?
我的控制器

import User from "../models/user";
import Stripe from "stripe";
const stripe = Stripe(process.env.STRIPE_SECRET);
export const createConnectAccount = async (req, res) => {
  console.log(req.user);
  try {
    const user = await User.findById(req.user._id).exec();
    console.log("USER ==> ", user);
    if (!user.stripe_account_id) {
      const account = await stripe.accounts.create({
        type: "express",
      });
      console.log("ACCOUNT ===>", account);
      user.stripe_account_id = account.id;
      user.save();
    }
  } catch (error) {
    res.status(500).json();
  }
};

我的中间件

var { expressjwt: jwt } = require("express-jwt");
// req.user
export const requireSignin = jwt({
    //secret, expiryDate
    secret: process.env.JWT_SECRET,
    algorithms: ["HS256"],
});

我的路线

import express from "express";

const router = express.Router();

import { requireSignin } from "../middlewares";

import { createConnectAccount } from "../controllers/stripe";

router.post("/create-connect-account", requireSignin, createConnectAccount);

module.exports = router;

我的授权控制器

import User from "../models/user";
import jwt from "jsonwebtoken";

export const register = async (req, res) => {
  console.log(req.body);
  const { name, email, password } = req.body;

  if (!name) return res.status(400).send("Name is required");
  if (!password || password.length < 6)
    return res
      .status(400)
      .send("Password is required and should be minimum 6 characters long");
  let userExist = await User.findOne({ email }).exec();
  if (userExist) return res.status(400).send("Email is taken");

  const user = new User(req.body);
  try {
    await user.save();
    console.log("User saved successfully", user);
    return res.json({ ok: true });
  } catch (err) {
    console.log("CREATE USER FAILED", err);
    return res.status(400).send("Error.Try again");
  }
};

export const login = async (req, res) => {
  // console.log(req.body);
  const { email, password } = req.body;
  try {
    //check if user with credentials
    let user = await User.findOne({ email }).exec();
    // console.log("USER EXISTS", user);
    if (!user) res.status(400).send("User with email not found");
    //compare password
    user.comparePassword(password, (err, match) => {
      console.log("COMPARE PASSWORD IN LOGIN ERR", err);
      if (!match || err) return res.status(400).send("Wrong password");
      //("GENERATE A TOKEN THEN SEND AS RESPONSE TO CLIENT");
      let token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {
        expiresIn: "7d",
      });
      res.json({
        token,
        user: {
          _id: user._id,
          name: user.name,
          email: user.email,
          createdAt: user.createdAt,
          updatedAt: user.updatedAt,
        },
      });
    });
  } catch (err) {
    console.log("LOGIN ERROR", err);
    res.status(400).send("Signin failed");
  }
};

我的终端输出

POST /api/login 200 1142.309 ms - 349
undefined
POST /api/create-connect-account 500 9.092 ms - -

标题

import axios from "axios";
export const createConnectAccount = async (token) => {
  await axios.post(
    `${process.env.REACT_APP_API}/create-connect-account`,
    {},
    {
      headers: {
         Authorization: `Bearer ${token}`, 
        },
    }
  );

};

sxissh06

sxissh061#

我很抱歉地告诉你,你的代码中还有其他错误。
我的猜测是你的res在auth控制器中写得不好,登录功能:

res.status(201).json({
        token :token,
        user: user
})

此外,当阅读您的令牌尝试进行身份验证时:使用相同的包比使用签名它的包更容易。

const jwt = require("jsonwebtoken");
exports. requireSignin = () => {
  return async (req, res, next) => {
    try {
      const token = req?.headers?.authorization?.split(" ")[1];
      const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
      const userId = decodedToken._id;
      const user = await User.findOne({ _id: userId });
      if (user) {
        req.auth = {
          user: user,
        };
      } else {
        throw new Error("user not found");
      }
      next();
    } catch (error) {
      console.log(error.message);
      res.status(401).json({ error: "failed to authenticate" });
    }
  };
};

但是你的代码很难读:为了让你更容易阅读,更清晰,试着用joy或者yup

有了这些,你将能够创建中间件,以避免在你的身体错误的条目:例如

if (!name) return res.status(400).send("Name is required");

会自动处理这些包
另外,你不应该在同一个项目中使用'import'和'require',选择其中一个
我希望这能有所帮助

j5fpnvbx

j5fpnvbx2#

尝试:

export const currentUser = async (req, res) => {
    console.log(req.auth);
    
};

req.user已移动到req.auth

相关问题