node.js - 如何在反应中处理响应
问题描述
我是新来的反应。目前我正在创建一个登录屏幕。我有这个代码:
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: })
});
但是当我按下提交按钮时,电子邮件和密码都控制台日志未定义。如何使用客户端和服务器之间的反应发送信息?先感谢您
解决方案
每当您使用 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 或其他网络语言的知识时,这个网站都非常有用。
推荐阅读
- python - 基于Django中两个可选字段的多对多关系
- javascript - 如何使用另一个数组的过滤索引过滤数组?
- php - 如何在此 oci_parse 语句中插入变量
- r - 如何使用 scale_color_brewer 修复“提供给离散比例的连续值”
- react-native - 使用反应导航时出现黑屏
- objective-c - 仅从 TextEdit 为 NSTextViews 获取某些功能的最佳方法
- .net - 如何从代码调用 TagPrefix/TagName .NET MVC 用户控件以呈现字符串
- python - np.where 和 for 循环中的重新索引错误
- ibm-watson - 如何使用 MQTT 订阅 Watson IoT 设备事件?
- python - 为什么随着网络训练的更多,GAN 生成的图像会变得更暗?