- npm install body-parser --save
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 启动静态资源服务
app.use(express.static('public'));
// 处理表单提交的数据(默认表单的提交格式)
app.use(bodyParser.urlencoded({extended : false}));
// 处理 json 形式数据
app.use(bodyParser.json());
app.post('/login', (req, res) => {
console.log(req.body);
if (req.body.username == 'admin' && req.body.password == '123') {
res.send('success post');
}else{
res.send('failure');
}
});
app.get('/login', (req, res) => {
console.log(req.query);
if (req.query.username == 'admin' && req.query.password == '123') {
res.send('success get');
}else{
res.send('failure');
}
});
app.put('/login', (req, res) => {
console.log(req.body);
if (req.body.username == 'admin' && req.body.password == '123') {
res.send('success put');
}else{
res.send('failure');
}
});
app.delete('/login', (req, res) => {
console.log(req.body);
if (req.body.id == '1234') {
res.send('success delete');
}else{
res.send('failure');
}
})
app.listen(3000, () => {
console.log('running……');
})
public/login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录页面</title>
<script src="jquery.js"></script>
<script>
$(function(){
// var obj = {
// id : '1111111',
// username : 'admin',
// password : 'abc'
// }
$("#but").click(function(){
$.ajax({
type : 'post',
url : '/login',
data : {username:'admin', password:'123'},
//data : JSON.stringify(obj),
success : function(data){
console.log(data); -----data是ajax返回的数据,打印在控制台
}
})
})
})
</script>
</head>
<body>
<form action="/login" method="get"> ---提交地址和提交的方式
用户名:<input type="text" name="username" value=""><br>
密 码:<input type="text" name="password" value=""><br>
<input type="submit" value="提交"> ----用于正常的表单提交
</form>
<input id="but" type="button" value="提交"> -----用于ajax
</body>
</html>