Home > Back-end >  fetching post request don't log success if the request succeed
fetching post request don't log success if the request succeed

Time:10-30

I'm trying to sign up new user, when I'm sending the post request the server register the user well, and I can see them in my data base, but I can't see the success log in my console (I can catch the error and it logs in my console).

Server side code:

var express = require("express");
const { Error } = require("mongoose");
const passport = require("passport");
var router = express.Router();
const User = require("../models/user");
const catchAsync = require("../utils/catchAsync");

router.post(
  "/register",
  catchAsync(async (req, res) => {
    try {
      const { email, username, password } = req.body;
      const user = new User({ email, username });
      await User.register(user, password);
    } catch (e) {
      throw new Error("Error signing up");
    }
  })
);

module.exports = router;

Client side code:

  const sumbitHandler = async (data) => {
  const { username, email, password } = data;
  try {
    await fetch("http://localhost:9000/users/register", {
      method: "POST",
      body: JSON.stringify({
        username,
        email,
        password,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => {
        if (res && !res.ok) {
          throw new Error("ERROR");
        }
        console.log("Success");
      })
      .catch((e) => {
        console.log(e.message);
      });
  } catch (e) {
    console.log(e.message);
  }
};

CodePudding user response:

  1. You are mixing the async/await style and the older .then() Promise-style. Choose one or the other (I strongly recommend async/await)

  2. You are not transforming fetch's response into JSON, leaving it in Promise state.

  3. Your server is never responding to the client! You need to add res.end(), res.send(), res.json() or something.

    const sumbitHandler = async (data) => {
        const { username, email, password } = data;
        try {
    
            const response = await fetch("http://localhost:9000/users/register", {...});
    
            const serverResponse = await response.text(); // or response.json() if your servers sends JSON back
    
            console.log("Success! serverResponse is = ", serverResponse ); // "Done!"
    
        } catch (e) {
            console.log(e.message);
        }
    };

Server :

...
await User.register(user, password);
res.send("Done!"); // or res.json({ status : "ok" }); etc.

  • Related