postObj.passwordAgain =
passwordAgain;
console.log(
'
注册
'
, userName, password, passwordAgain)
fetch(
"
/register
"
, {
method:
"
POST
"
,
headers: {
'
Content-Type
'
:
'
application/x-www-form-urlencoded
'
body: `userName
=${postObj.userName}&password=${postObj.password}&passwordAgain=
${postObj.passwordAgain}`
}).then(function(res) {
return
res.json();
}).then(function (data) {
console.log(data)
这里的前端使用的是react,前端使用fetch来请求,由于fetch支持promise方式,所以使用then进行链式调用。
发送json数据,这里使用的是es6的模板字符串进行拼接的。 这样发送的数据就符合表单的形式了。
第一步:接收到res并将其通过 return res.json() 转化为 json数据。
第二步:然后接着调用then就可以得到json数据了 。
后端:
router.post(
'
/register
'
, function (req, res) {
console.log('注册传给后台的数据', req.body.userName, req.body.password, req.body.passwordAgain)
if (req.body.password == req.body.passwordAgain) {
var newUser = new User({
name: req.body.userName,
password: req.body.password
// 如果符合条件,就注册该用户,将数据保存在数据库。
newUser.save(function (err, user) {
if (err) {
console.log(err)
} else {
var response = {
code: 200,
message: "用户注册成功!"
}
res.json(response);
console.log(
'
注册成功
'
)
}
else
{
console.log(
'
注册失败
'
)
后端返回的很简单,就是直接在符合条件的情况下使用 res.json() 来传递json了,其中的值是一个对象,res.json() 会自动将至转化为json字符串并返回给前端。
参考文章: https://stackoverflow.com/questions/29775797/fetch-post-json-data