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