使用req.body.xxx來獲取請求數據(測試中文可用,不亂碼):
~~~
var username = req.body.username
var pwd = req.body.pwd
~~~
以用戶登錄為例:
login.html
~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="../javascripts/jquery-3.2.0.min.js" ></script>
<script>
$(function(){
$("#btn_login").click(function(){
$.ajax({
url:"../users/login",
type:"post",
data:{username:$("#username").val(),pwd:$("#pwd").val()},
dataType:"json",
success:function(data)
{
if(data.result)
{
location.href = "main.html";
}
else{
alert("登錄失敗");
}
}
});
});
})
</script>
</head>
<body>
<input type="text" name="username" id="username" />
<input type="password" name="pwd" id="pwd" />
<button id="btn_login">登錄</button>
</body>
</html>
~~~
user.js
~~~
router.post('/login', function(req, res, next) {
var username = req.body.username;
var pwd = req.body.pwd;
res.send('{"username":"'+username+'","pwd":"'+pwd+'"}');
});
~~~
請求路徑為rest時,使用以下方式獲取:
~~~
router.get('/rest/:id', function(req, res, next) {
//獲取表單數據
var username = req.params.id;
console.log(username);
res.send('respond with a resource');
});
~~~
響應:
1. 響應字符串:
~~~
res.send('respond with a resource');
~~~
2. 響應ajax
~~~
res.send('{"result":true}');
res.json(obj);
~~~
3. 響應html
~~~
router.get('/helloworld', function(req, res, next) {
res.redirect("html/helloworld.html");
});
~~~
4. 響應模板頁面
~~~
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
~~~