曾经,我非常羡慕那些人见人爱的人,我也想要变成那样,可是后来我才明白人见人爱也是需要天赋的,后来我开始默默努力,我想,就算我不能让每个人都喜欢我,至少因为我做的努力能得到别人的尊重。

express后端和fetch前端的json数据传递

  在使用express做后端,前端使用fetch API来请求后端时,一般都是用 JSON 数据进行通信的。 下面是一个简单的例子:

 

前端

        if (up) {
            var passwordAgain = this.state.passwordAgain;

            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

posted @ 2017-07-28 21:06  Wayne-Zhu  阅读(5598)  评论(0编辑  收藏  举报

一分耕耘,一分收获。