gpt4 book ai didi

node.js - "What is causing this ' 表单提交不正确 ' response to my simple node post request?"

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:00 25 4
gpt4 key购买 nike

为我稍后要构建的应用程序制作注册页面。刚刚创建了一个简单的 Node 服务器,它在端口 3000 上运行。我创建了一个带有简单表单界面的 React 应用程序,在端口 3001 上运行。用户填写表单并点击注册按钮,这应该将电子邮件和密码发送到/register 的 post 路由。

但我每次都会收到“表单提交不正确”的信息。它看起来只是网络 Pane 中的一个 json 对象“{email: dummy@email,password: 123}”,所以我不确定这意味着什么......

onSubmitRegister = () => {
fetch('http://localhost:3000/register', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then(response => response.json())
.then(data => console.log(data));
}

Node 服务器如下所示:

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));

app.get("/", (req, res) => {
res.send("Hello");
})

app.post("/register", (req, res) => {
console.log(req.body);
})

app.listen(3000, () => {
console.log("Server started on port 3000");
});

目前,我只希望它能够控制台记录 req.body,因此我知道在继续构建 MongoDB 数据库并开始向集合添加文档之前一切正常。 Stack Overflow 和我在 google 上搜索过的其他论坛主题建议检查标题是否正确。这对我来说看起来不错。我错过了什么吗?

编辑:这就是表单的样子,整个渲染函数:

  render(){
return(
<div>
<div className="text-center">
<form className="form-signin">
<h1 className="h3 mb-3 font-weight-normal">Ohaii Sign Up</h1>
<label for="inputEmail" className="sr-only">Email address</label>
<input
type="email"
id="inputEmail"
className="form-control"
placeholder="Email address"
required=""
autofocus=""
onChange={this.onEmailChange}
/>
<label for="inputPassword" className="sr-only">Password</label>
<input
type="password"
id="inputPassword"
className="form-control"
placeholder="Password"
required=""/>
<label for="inputPassword" className="sr-only">Password</label>
<input
type="password"
id="confirmPassword"
className="form-control"
placeholder="Confirm Password"
required=""
onChange={this.onPasswordChange}
/>
<div className="btn btn-block btn-social btn-google" style={{'color': '#fff'}}>
<span className="fa fa-google"></span> Sign Up with Google
</div>
<div className="btn btn-block btn-social btn-facebook" style={{'color': '#fff'}}>
<span className="fa fa-facebook"></span> Sign Up with Facebook
</div>
</form>
</div>
<button
onClick={this.onSubmitRegister}
className="btn btn-lg btn-primary btn-block"
>Register</button>
</div>
)
}

最佳答案

当您发送 JSON 数据时(您的正文是 JSON 并且您正在设置 JSON 内容类型),我建议将 bodyParser 中间件更改为:

app.use(bodyParser.json());

至少,在我的快速测试中,我能够从浏览器发送数据并在服务器上看到它。然而,对于 bodyParser.urlencoded ,情况并非如此,我没有得到与您相同的错误。

另外,你应该从服务器返回一些响应,例如我使用:

app.post("/register", (req, res) => {
console.log(req.body);
res.end("{}");
});

关于node.js - "What is causing this ' 表单提交不正确 ' response to my simple node post request?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com