express框架
程序员文章站
2022-07-10 16:11:12
...
express框架是nodejs的一个优秀的web框架,继承了许多简单易用的方法
1、创建web服务器并接受get请求
首先要安装express
npm install express --save
const express = require('express');
const app = express();
app.get('/getName', function(req, resp){
resp.send('孙悟空');
});
app.listen('8000', function(){
console.log('server is running at port 8000...');
});
2、post请求并获请求取参数
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/getName', function(req, resp){
resp.send('孙悟空');
});
app.post('/test_post', urlencodedParser, function (req, res) {
var response = {
"first_name":req.body.first_name,
"last_name":req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
app.listen('8000', function(){
console.log('server is running at port 8000...');
});
<html>
<body>
<form action="http://127.0.0.1:8000/test_post" method="POST">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
上一篇: HTTP报文格式详解