【发布时间】:2020-04-24 04:30:06
【问题描述】:
您好,请帮助苦苦挣扎的开发人员。
我整天都在努力解决这个问题,但无济于事。基本上我想做的就是从我的 AddUsers 类中发布,并将其存储到我的 sql 数据库中。这是一个非常简单的查询,但让我变得更好!状态会随着变化而更新,但似乎是 server.js 的问题(错误包含在帖子底部)
服务器.js
app.post("/admin-Add-Users", function(req, res) {
var request = new sql.Request();
// query to the database and get the records
request.query(
"insert into Login (email, password) values ('" +
req.body.email +
"','" +
req.body.password +
"')",
function(err, recordset) {
if (err) console.log(err);
}
);
res.send({ message: "Success" });
});
AddUsers 类
class AddUsers extends React.Component {
constructor() {
super();
this.state = { users: [], email: "", password: "" };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const data = { email: this.state.email, password: this.state.password };
fetch("/admin-Add-Users", {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log("Success:", data);
})
.catch(error => {
console.error("Error:", error);
});
}
render() {
console.log(this.state.users);
return (
<div>
<LoginForm></LoginForm>
<form>
<input
type="text"
placeholder="email"
value={this.state.email}
onChange={e => this.setState({ email: e.target.value })}
/>
<input
type="text"
placeholder="password"
value={this.state.password}
onChange={e => this.setState({ password: e.target.value })}
/>
<input type="submit" onClick={this.onSubmit} />
</form>
</div>
);
}
}
ReferenceError: email is not defined
更新:在尝试了我得到的建议后,我现在恢复了一个新错误。
Error: SyntaxError: Unexpected token < in JSON at position 0
【问题讨论】:
-
请不要以使现有答案无效的方式更改您的问题。
-
请注意,您的
res.send({ message: "Success" });将始终被发送,无论 sql 请求的结果如何,因为您已将其放在回调之外。 -
我重新编辑了标题
-
你添加
app.use(express.urlencoded());到服务器了吗?
标签: javascript node.js json reactjs express