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

san*_*der 1 javascript promise reactjs fetch-api

我试图打印出 Fetch 承诺的值,但它undefined在我 console.log 时显示。

当我在 Postman 中尝试时,Php 服务器使用 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.');
                }
Run Code Online (Sandbox Code Playgroud)

bad*_*dri 7

您必须使用格式化程序来记录或处理数据,以下是一种方法

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);
  });
})    
Run Code Online (Sandbox Code Playgroud)