Node.js Express 框架 POST方法详解
POST方法
以下实例演示了在表单中通过POST方法提交两个参数,我们可以使用server.js文件内的process_post路由器来处理输入:
index.htm文件代码修改如下:
<html> <body> <formaction="http://127.0.0.1:8081/process_post"method="POST"> FirstName:<inputtype="text"name="first_name"><br> LastName:<inputtype="text"name="last_name"> <inputtype="submit"value="Submit"> </form> </body> </html>
server.js文件代码修改如下:
varexpress=require('express');
varapp=express();
varbodyParser=require('body-parser');
//创建application/x-www-form-urlencoded编码解析
varurlencodedParser=bodyParser.urlencoded({extended:false})
app.use(express.static('public'));
app.get('/index.htm',function(req,res){
res.sendFile(__dirname+"/"+"index.htm");
})
app.post('/process_post',urlencodedParser,function(req,res){
//输出JSON格式
response={
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("应用实例,访问地址为http://%s:%s",host,port)
})
执行以上代码:
$nodeserver.js
应用实例,访问地址为http://0.0.0.0:8081
浏览器访问http://127.0.0.1:8081/index.htm
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
