express後端和fetch前端的json數據傳遞

  在使用express作後端,前端使用fetch API來請求後端時,通常都是用 JSON 數據進行通訊的。 下面是一個簡單的例子:前端

 

前端react

        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進行鏈式調用。es6

  發送json數據,這裏使用的是es6的模板字符串進行拼接的。 這樣發送的數據就符合表單的形式了。數據庫

  第一步:接收到res並將其經過 return res.json() 轉化爲 json數據。express

  第二步:而後接着調用then就能夠獲得json數據了 。 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);
promise

 } }); console.log('註冊成功') } else { console.log('註冊失敗') } });

  後端返回的很簡單,就是直接在符合條件的狀況下使用 res.json() 來傳遞json了,其中的值是一個對象,res.json() 會自動將至轉化爲json字符串並返回給前端。 app

 

 

參考文章: https://stackoverflow.com/questions/29775797/fetch-post-json-datapost

相關文章
相關標籤/搜索