在React中处理fetch()调用的结果

我正在尝试为具有Express后端的React Client应用创建登录页面。

// Except from App.js in Client

  async function performLogin (values) {
    const { email:username,password } = values;
    const credentials = { username,password };
    const response = await fetch('http://localhost:4000/tokens/',{
      method: 'POST',headers: new Headers({
        'Content-Type': 'application/json','accept': 'application/text',}),body: JSON.stringify(credentials)
    });
    console.log('Result from backend token: '+JSON.stringify(response));
  };
// tokens.js from backend

const jwt = require('jsonwebtoken');
const findUser = require('../lib/find-user');

const signature = process.env.SIGNATURE;
const expiresIn = process.env.EXPIRESIN;

const createToken = (user) =>
  jwt.sign(
    { userId: user.id },signature,{ expiresIn: expiresIn }
  );

// Code used to respond to /tokens/ path

let createTokenRoute = (req,res) => {
  let credentials = req.body;
  console.log('Credentials: '+JSON.stringify(credentials));
  let user = findUser.byCredentials(credentials);
  console.log('User: '+JSON.stringify(user));
  if (user) {
    let token = createToken(user);
    res.status(201);
    console.log('Token: '+JSON.stringify(token));
    res.send(token);
  } else {
    res.sendStatus(422);
  }
};

从Postman ping /tokens/路径后,按预期方式,我得到了一个作为文本返回的令牌,后端的控制台忠实地吐出了:

Credentials: {"username":"rd@example.com","password":"12345678"}
User: {"id":"3","username":"rd@example.com","name":"Richard","password":"12345678"}
Token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c... etc."

邮递员向我展示了预期的结果:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c... etc.

但是,当从App.js代码中调用时,后端的行为与以前一样,列出了凭据,用户和令牌...但是客户端的浏览器控制台给了我一个空对象:

Result from backend token: {}

我尝试使用accept标头,但是我的无知让我看不出我要去哪里。我相当确定这完全是愚蠢的;-)


编辑:

所以我重写了performLogin函数:

  async function performLogin (values) {
    const { email:username,body: JSON.stringify(credentials)
    });
    const result = await response.json();
    console.log('Result from backend token: '+result);
  };

现在页面崩溃了...

Unhandled Rejection (SyntaxError): The string did not match the expected pattern.
(anonymous function)
src/App.js:55
  52 |     }),53 |     body: JSON.stringify(credentials)
  54 |   });
> 55 |   const result = await response.json();
     | ^  56 |   console.log('Result from backend token: '+result);
  57 | };
  58 | 
View compiled
canjiahuiyi 回答:在React中处理fetch()调用的结果

  

从后端将响应作为json发送

 res.status(201).json({ token : token });

  

从前端接受json

'Accept': 'application/json'

希望这会对您有所帮助。不过,如果您有任何问题,请告诉我。

本文链接:https://www.f2er.com/3150833.html

大家都在问