skip to Main Content

I’ve been stuck on this for hours would really appreciate if anyone can help!
Below is a registration form, where I post the user info to mongodb.
For some reasons, when I do an axios post, on the network tab in inspect it would show that my request is pending. However, when looking at mongodb, the user is registered in my mongodb collection.
This is my frontend part of it:

async function register(e) {
  e.preventDefault();
  await axios.post("/register", { fname, lname, username, email, password });
}

I have the following backend:

dotenv.config();
mongoose.connect(process.env.MONGO_URL);
const jwtSecret = process.env.JWT_SECRET;
const app = express();
app.use(express.json());
app.use(
  cors({
    credentials: true,
    origin: process.env.CLIENT_URL,
  }),
);
app.post("/register", async (req, res) => {
  const { fname, lname, username, email, password } = req.body;
  try {
    const myUser = await User.create({
      fname,
      lname,
      username,
      email,
      password,
    });
    jwt.sign({ userId: myUser._id }, jwtSecret, {}, (err, token) => {
      if (err) throw err;
      res.cookie("token", token).status(201).json({
        _id: createdUser._id,
      });
    });
  } catch (err) {
    if (err) throw err;
    res.status(500).json("error");
  }
});

I really don’t know how to solve this, Content-Type is set to application/json correctly as the registration form is using cors. Any help would be appreciated!

2

Answers


  1. The error is here:

     res.cookie("token", token).status(201).json({
            _id: createdUser._id,
          });
    

    You’re trying to access _id of undefined. The variable createdUser doesn’t exists, you should use myUser instead.

     res.cookie("token", token).status(201).json({
            _id: myUser._id,
          });
    

    But you should look into the correct way of handling errors in express. In the current version of express (4.18.1) you have to pass the errors to the next function.

    Express will support throwing exceptions in async functions starting from the version 5, but for now you have to use the next()

    Source: expressjs docs

    Login or Signup to reply.
  2. It seems correct and perfect needs to do small changes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search