1.在表单中通过 GET 方法提交两个参数,我们可以使用 server.js 文件内的 process_get 路由器来处理输入:
首先需要安装以下依赖:
$ cnpm install express --save
$ cnpm install body-parser --save
index.html
<!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>
</head>
<body>
<form action="http://127.0.0.1:3000/process_get" method="GET">
First Name : <input type="text" name="first_name"><br>
Last Name : <input type="text" name="last_name"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
server.js
var express = require('express');
var app = express();
//app.use(express.static('public'));
//读取index.html文件,在浏览器窗口进行展现
app.get('/index.html',function(req,res){
res.sendfile(__dirname + '/' + 'index.html');
})
//接收前台提交的数据
app.get('/process_get',function(req,res){
//输出json格式
var response = {
"first_name":req.query.first_name,
"last_name":req.query.last_name
};
console.log(response);
res.send(JSON.stringify(response));
})
var server = app.listen('3000',function(){
var host = server.address().address;
var port = server.address().port;
})
2.在表单中通过 POST方法提交两个参数,我们可以使用 server.js 文件内的 process_post 路由器来处理输入:
index.html
<!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>
</head>
<body>
<form action="http://127.0.0.1:3000/process_post" method="POST">
First Name : <input type="text" name="first_name"><br>
Last Name : <input type="text" name="last_name"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
server.js
var express = require('express');
var app = express();
var bodyParse = require('body-parser');
//创建application/x-www-form-urlencoded编码解析
var urlencodedParse = bodyParse.urlencoded({extended:false});
app.use(express.static('public'));
app.get('/index.html',function(req,res){
res.sendFile(__dirname + "/" + 'index.html');
})
app.post('/process_post',urlencodedParse,function(req,res){
//输出json格式
var response = {
"first_name":req.body.first_name,
"last_name":req.body.last_name
}
console.log(response);
res.send(JSON.stringify(response));
})
var server = app.listen(3000,function(){
var host = server.address().address;
var port = server.address().port;
})