获取承诺值

Getting a promiseValue

我是 javascript 的新手,我想获取在 POST[= 之后生成的 promiseValue 中的值31=]。 API 正在连接带来一个 json 对象,如下所示:

{
    "message": "User logged in successfully",
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MzE4NTA2ODcsImlhdCI6MTUzMTg0ODg4NywidXNlcm5hbWUiOiJ5b3VxQGdtYWlsLmNvbSJ9.oTwcHkW64RS7ooz5_dzrmlvflI4Eg2Y39hGM0D-wZkY"
}

但是在 google chrome 中,我收到它作为 PromiseValue,所以我的目标是获取或打印 消息token 值来自 promiseValue.

下面是显示 promiseValue 我得到的图像:

the output

以下是目前的代码:

fetch('https://xxxxxx.xxxxxxxx',
    {
        method: 'POST',
        headers: {
            'Accept': 'application/json,text/plain,*/*',
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: password
        })

    }).then((res) =>{
        if(res.status=='401'){
            console.log(res.status)
            console.log(res.json())
            alert("Sorry please, invalid username or password.");
        }
        else if (res.status='200')
        {
            console.log(res.status)
            console.log(res.json())

        }
    })
    .then((data) => {
        console.log(" my data :   "+data)
      })

res.json()return是一个承诺。您需要从第一个 then 处理程序中 return 它才能在第二个 then 处理程序中使用它:

fetch(...)
  .then(res => {
    if (res.status == '401') {
      ...
    } else if (res.status = '200') {
      ...
    }

    return res.json(); // <-- Add this return call
  })
  .then(res => {
    console.log(" my data :   " + res);
    console.log(res.token, res.message); // <-- Access the response keys here
  });
fetch(...)
 .then(res => {
    if (res.status == '401') {
      throw 'Some error message'; // <-- Add this throw exeption
      ...
    } else if (res.status = '200') {
      ...
    }

   return res.json(); // <-- Add this return call 
   })
   .then(res => {
      console.log(" my data :   " + res);
      console.log(res.token, res.message); // <-- Access the response keys here
   })
   .catch(e => console.error(e)) // <-- Catch your errors here