1

I hope I didn't repeat this question, but i didn't find any on stackoverflow.

this is a login method, i send a 200 status code with the user object as a response when someone login correctly, but on the client side i only get the default response of 200, and when I login with the wrong password I get 500 default response with no any data of what I send! no error messages and no objects when I sign-in correctly.

this is the middleware

i use

app.use(express.json());
app.use(bodyParser.json());

the login method

exports.logIn =async (req,res)=>{

 let {email,password} = req.body;
 let user;
 let passwordCorrect;
 try{
   user = await UserModel.findOne({email:email});

   if(user){
       console.log("user found")
     passwordCorrect= await bcryptjs.compare(password,user.password);

     if(passwordCorrect){
       console.log("password correct")

       res.json({user:user})
     }else{
       console.log("password not")

       throw new Error("password is wrong");

     }

   }else{
     console.log("user not found ")

     throw new Error("This user is not in our system");
   }

 }catch(err){
   console.log("catched error  ")
   console.log(err)

   res.status(500).json({
     status:'fail',
     message:err.message
   })

 }

}


and this is the response i get when i login correctly, the response is missing the data that am sending from server, and incase of wrong password , i recive 500 without the error message that i send from server

Response {type: "cors", url: "http://localhost:8080/api/user/login", redirected: false, status: 200, ok: true, …}
type: "cors"
url: "http://localhost:8080/api/user/login"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: false
__proto__: Response

from client side where i use react

  try{

            const user  = await fetch("http://localhost:8080/api/user/login",{
                headers:{
                    "Content-Type":"application/json"
                },
                method:"POST",
                body:JSON.stringify(data)
            });

              if(user.ok){
               // auth.login();
               console.log('ok')
               console.log(user)
            }else{
                console.log('not ok')

                console.log(user)

                setError(user.message)
            }

         }catch(err){

            console.log("error ")
            console.log(err);
            setError(err)

 }

and this is the middleware to accept requests from another domains

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Accses-Control-Allow-Methods","GET,POST,DELETE,PATCH");
console.log(req.body);
    next();
  });
4
  • 1
    Can you have an example of how you send the request and the response you are receiving ? Commented Jan 18, 2020 at 18:16
  • Yes , i will edit my question Commented Jan 18, 2020 at 18:20
  • 1
    Please use return while you are returning your response in both the case 1. Success Response 2. Error Response Commented Jan 18, 2020 at 19:11
  • have you tried ` next(err)` inside you catch? Commented Jan 18, 2020 at 19:41

1 Answer 1

1

Javascript fetch api returns a promise containing the response. This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method.

So your code should be:

try {
  const response = await fetch("http://localhost:8080/api/user/login", {
    headers: {
      "Content-Type": "application/json"
    },
    method: "POST",
    body: JSON.stringify(data)
  });

  if (response.ok) {
    console.log("ok");
    let user = await response.json();
    console.log("user: ", user);
  } else {
    console.log("not ok");
    console.log(response);
    setError(response.message);
  }
} catch (err) {
  console.log("error ");
  console.log(err);
  setError(err);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.