如何在 ReactJs 中打印 Fetch 承诺值?

How do I print Fetch promise value in ReactJs?

我正在尝试打印出 Fetch promise 的值,但是当我 console.log 它时它显示 undefined

Php 当我在 Postman 中尝试时,服务器使用 http 正文中的 jwt 令牌响应此提取。

 fetch("http://localhost:8001/api/login", {
                        method: 'post',
                        headers: {
                            "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
                       },
                        body: 'username=' + this.state.username + '&password=' + this.state.password
                    })
                        .then(function (responseObject) {
                            console.log('Request succeeded with Response object', responseObject);

                        })
                        .then(function (result){
                            console.log(result);
                        })
                        .catch(function (error) {
                            console.log('Request failed', error);
                        });
                }else{
                    console.log('You must enter username, password.');
                }

您必须从 responseObject 和 return 中调用 json()text() 之类的结果才能将其放入 result

您必须使用格式化程序来记录数据或对数据执行某些操作,以下是一种实现方式

fetch('http://localhost:8001/api/login').then(
function(response) {
  if (response.status !== 200) {
    console.log('Problem in fetching');
    return;
  }
  response.text().then(function(data) {
    console.log(data);
  });
})    
            fetch("http://localhost:8001/api/login", {
                method: 'post',
                headers: {
                    "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
               },
                body: 'username=' + this.state.username + '&password=' + this.state.password
            })
                .then(function (responseObject) {
                    console.log('Request succeeded with Response object', responseObject);
                    return responseObject;
                })
                .then(function (result){
                    console.log(result.text());
                })
                .catch(function (error) {
                    console.log('Request failed', error);
                });
        }else{
            console.log('You must enter username, password.');
        }

通过将 return response Object 添加到第一个 .then 子句和 console.log(responseObject.text ()); 到第二个 .then 子句,现在我的 jwt 令牌打印出来了。