express後端和fetch前端的json資料傳遞

來源:互聯網
上載者:User

標籤:通過   amp   接收   his   var   express   http   rom   eth   

  在使用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

express後端和fetch前端的json資料傳遞

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.