【问题标题】:Getting a promiseValue获得一个 promiseValue
【发布时间】:2018-12-25 22:22:37
【问题描述】:

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

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

但在 google chrome 中,我将它作为 PromiseValue 接收,所以我的目标是获取或打印 messagetokenpromiseValue

下图显示了我得到的 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)
      })

【问题讨论】:

    标签: javascript google-chrome post fetch-api


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      res.json() 返回一个承诺。您需要从第一个 then 处理程序中返回它以在第二个 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
        });
      

      【讨论】:

      • 如何从数据中获取特定的令牌和消息?
      • @LutaayaHuzaifah -- 请查看更新后的答案。
      猜你喜欢
      • 2020-12-03
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多