▌非AJAX作法(表單做法)
- 用form表單把資料post到特定路徑下面
- 此做法會導致畫面重新reload
- 表單資料會出現在
req.body
(name會是資料名稱) - Name是會POST到後端的重要參數(id只會在前端)
//html
<form action="/" method="POST">
<input type="text" placeholder="IG帳號" name="account" id="submit_input" value="">
<button id="button-describe" type="submit">訂閱</button>
</form>
//express
app.post('/', function (req, res) {
console.log(req.body.account);
})
▌AJAX作法(JQuery作法)
//html
<input type="text" placeholder="IG帳號" id="subscriptionAccount" value="">
<button id="subscriptionButton" type="submit">訂閱</button>
- 取得input資料,然後把他ajax到伺服器
- data:{“content”:subscriptionAccount} 會把一個物件傳到後面
- success:function(res) 可以得到後端伺服器的res(後端自己寫的)
//JQuery
$('#subscriptionButton').on('click', function () {
var subscriptionAccount = $('#subscriptionAccount').val();
if (subscriptionAccount == '') {
toastr.info("請輸入帳號")
}
else{
$.ajax({
url: "/newaccount",
dataType: "json",
data:{"content":subscriptionAccount},
method:"post",
success:function(res){
console.log(res)
if(res.success){
toastr.info("訂閱成功");
}else{
toastr.info("帳號已存在");
}
}
});
}
});
//Express.JS
app.post('/newaccount', function (req, res) {
var content = req.body.content;
var connectTofirebase = fireData.ref("AccountData").push();
if(allAccount.indexOf(content) == -1){
connectTofirebase.set({
"account": content,
"date": Date.now()
}).then(function(){
fireData.ref('AccountData').once('value',function(snapshot){
res.send({
"success":true,
"result":snapshot.val(),
"message":"訂閱成功"
});
});
});
}
else {
res.send({
"success":false,
"message":"已存在該帳號"
});
}
})
▌後端的Express的API寫法
- API寫法
res.send({
"success":true,
"result":snapshot.val(),
"message":"訂閱成功"
});
▌不管怎樣都要安裝body-parser
- body-parser可以解析前端POST過來的「資料」
npm install body-parser //安裝body-parser
▌設置參數
//express.js
var bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: false
}));