首页 > 解决方案 > 如何在反应中处理响应

问题描述

我是新来的反应。目前我正在创建一个登录屏幕。我有这个代码:

function login(e) {
    fetch('/login')
      .then(response => {
        if(response === 'fail'){
            return(SignIn());
        }else{
            return(Ide());
        }
      })
      .then((proposals) => { 
        console.log(proposals);
        this.setState({ proposals }); 
      });
  }
export default function SignIn() {
  const classes = useStyles();

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign in
        </Typography>
        <form className={classes.form} noValidate>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label="Email Address"
            name="email"
            autoComplete="email"
            autoFocus
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="Password"
            type="password"
            id="password"
            autoComplete="current-password"
          />
          <Button
            type="submit"
            fullWidth
            onClick={login}
            variant="contained"
            color="primary"
            className={classes.submit}
          >
            Sign In
          </Button>
        </form>
      </div>
    </Container>
  );

然后登录处理程序

app.get('/login', (req, res, next) => {
  const { email, password } = req.body;
  console.log(email, password); 
  //User.find({email: })
});

但是当我按下提交按钮时,电子邮件和密码都控制台日志未定义。如何使用客户端和服务器之间的反应发送信息?先感谢您

标签: node.jsreactjs

解决方案


每当您使用 fetch 作为向上面的“/login”等端点发送信息的一种方式时,都需要将 req.body 添加为 fetch 调用的一部分。为此,人们通常会这样做

fetch('/login', {
body: (whatever you send in the form of one object)
});

然后,作为第二个参数传入的主体可以用作 req.body 在您的控制台中记录它的代码。

但不建议这样做,因为 GET 命令通常没有将正文作为第二个参数传递。通常 POST 和 PUT 命令具有主体,以便于添加和更改数据。我建议做的是:

fetch('/login/' + email + '/' + password);

这允许电子邮件和用户名对象成为您的 url 的一部分,供您的后端使用。这是人们在不传递正文的情况下执行 GET 命令的方式之一。使用新格式,您应该将后端更改为:

app.get('/login/:email/:password', (req, res) => {
const email = req.params.email;
const password = req.params.password;
console.log(email, password);

使用 :email 和 :password 在 url 中,这使您可以使用 req.params 然后直接调用每个标识符作为最后一个值。

顺便说一句,如果你觉得上面的 fetch 调用看起来对 + 命令很乱,你可以这样做:

fetch(`/login/${email}/${password}`);

哪些是模板文字,通过将值直接添加到字符串中,可以更轻松地阅读代码。(注意他们使用 1 键旁边的 ` 键而不是 ' 或 ")

此外,如果您想了解有关 fetch 命令的更多信息,我建议您从MDM 文档开始。每当您需要学习有关 JS 或其他网络语言的知识时,这个网站都非常有用。


推荐阅读