使用express接受get和post數據,首先下載我們所需要的框架 express和express-static
npm install express
npm install express-static
然后使用express創建服務器并接受get和post數據
get數據
js代碼:
const express=require('express');
var server=express();
server.listen(8080);
server.use('/',function(req,res){
console.log(req.query);
})
html代碼:
<form action='http://localhost:8080' method='get'>
用戶名: <input type="text" name='user'>
密 碼: <input type="password" name='pass'>
<input type="submit" value='提交'>
</form>
我們開啟服務器,然后打開html頁面,輸入用戶名和密碼,點擊提交,我們在命令行中就可以看到我們輸入的信息會在命令行中顯示
post數據
接受post數據相對get數據來說要稍微復雜點,接受post數據需要借助 “中間件” body-parser
所以首先我們需要下載一下body-paser
npm install body-parser
js代碼
const express=require('express');
const bodyParse=require('body-parse');
var server=express();
server.listen(8080);
server.use(bodyParser.urlencoded({}));
server.use('/',function(req,res){
console.log(req.body);
})
html代碼:
<form action='http://localhost:8080' method='post'>
用戶名: <input type="text" name='user'>
密 碼: <input type="password" name='pass'>
<input type="submit" value='提交'>
</form>
我們開啟服務器,然后打開html頁面,輸入用戶名和密碼,點擊提交,我們在命令行中就可以看到我們輸入的信息會在命令行中顯示
鏈式操作
const express=require('express');
const bodyParse=require('body-parser');
var server=express();
server.listen(8080);
//鏈式操作://請求同一個地址才叫做鏈式操作
server.use('/',function(req,res,next){
console.log('a');
next();//next參數的意思是說執行完a如果還要繼續向下執行就要寫next,不執行接下來的東西就不需要寫
})
server.use('/',function(req,res,next){
console.log('b')
})
自己仿寫一個body-parse
const express=require('express');
const querystring=require('querystring');//把數據輸出在json中
var server=express();
server.listen(8080);
server.use(function(req,res,next){
var str='';
req.on('data',function(data){
str+=data;
})
req.on('end',function(){
req.body=querystring.parse(str);
next();
})
})
server.use('',function(req,res){
console.log(req.body);
})