簡體   English   中英

從 API Node JS 獲取不正確的數據

[英]Getting not correct data from API Node JS

我希望我沒有重復這個問題,但我沒有在 stackoverflow 上找到任何問題。

這是一種登錄方法,當有人正確登錄時,我發送一個帶有用戶對象的 200 狀態代碼作為響應,但在客戶端我只得到 200 的默認響應,當我使用錯誤的密碼登錄時,我得到 500 默認響應沒有我發送的任何數據的響應! 當我正確登錄時,沒有錯誤消息和對象。

這是中間件

我用

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

登錄方式

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
   })

 }

}


這是我正確登錄時得到的響應,響應缺少從服務器發送的數據,如果密碼錯誤,我收到 500 沒有從服務器發送的錯誤消息

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

從我使用反應的客戶端

  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)

 }

這是接受來自其他域的請求的中間件

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();
  });

Javascript fetch api返回一個包含響應的承諾。 這只是一個 HTTP 響應,而不是實際的 JSON。 為了從響應中提取 JSON 正文內容,我們使用json()方法。

所以你的代碼應該是:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM