关于前端发送请求,后台根据请求方式不同,做出不同的处理的小demo。
后台部分(根据前端发来的type类型不同来处理)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36const express = require('express');
const app = express();
const bodyParser = require('body-parser');
//挂载内置中间件
app.use(express.static('public'));
//挂载参数处理中间件(post)
app.use(bodyParser.urlencoded({extended:false}));
//处理json格式的参数
app.use(bodyParser.json())
//处理get提交参数
app.get('/login',(req,res)=>{
let data = req.query;
console.log(data);
res.send('get data')
})
//处理post提交参数
app.post('/login',(req,res)=>{
let data = req.body;
if(data.username == 'admin' $$ data.password == '123'){
res.send('success');
}else{
res.send('failure);
}
})
//处理put提交参数
app.put('/login',(req,res)=>{
res.end('put data');
})
//处理delete提交参数
app.delete('/login',(req,res)=>{
res.end('delete data');
})
app.listen(3000,()={
console.log('running...');
});
前端部分(在public文件夹下)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script type="text/javascript" src="jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function(){
$('btn').click(function(){
var obj = {
username: $('#username').val(),
password: $('#password').val()
}
$.ajax({
type : 'post',
url: 'http://localhost:3000/login',
contentType: 'application/json',
dataType:'text',
data:JSON.stringify(obj),
success:function(data){
console.log(data)
}
})
})
})
</script>
</head>
<body>
<form action="http://localhost:3000/login" method="get">
用户名:<input type="text" name="username" id="username"><br>
密码: <input type="password" name="password" id="password"></br>
<input type="button" id="btn" value="提交">
</form>
</body>
</html>