文档手册:http://expressjs.com/en/4x/api.html#req.app
1,新建一个空的文件夹:hello-express
2,文件夹中新建文件express.js
3,初始化文件夹
npm install
4,安装express和nodemon
npm install express -save
npm install -g nodemon
5,
var express=require('express');
var app=express();
app.get('/home',function(request,response){
response.send(
JSON.stringify({
name:'11.',
age:12
})
)
});
app.listen(3000);
console.log('listen start')
6,路由参数
var express = require('express');
var app = express();
app.get('/profile/:id/user/:name', function(req, res) {
console.dir(req.params);
res.send("You requested to see a profile with the name of " + req.params.name);
});
app.get('/ab?cd', function(req, res) {
res.send('/ab?cd'); //正则匹配:问号前面的b可以出现一次或者不出现
})
app.listen(3000);
console.log('listening to port 3000');
7, 查询字符串(get请求)
request.query
var express=require('express');
var app=express();
app.get('/ab?cd',function(request,response){
response.send(
request.query
)
});
app.listen(3000);
console.log('listen start')
8:post请求
使用库body-parser
地址:https://github.com/expressjs/body-parser
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/', function(req, res) {
console.dir(req.query);
res.send("home page: " + req.query.find);
});
app.post('/', urlencodedParser, function(req, res) {
console.dir(req.body);
res.send(req.body.name);
});
app.post('/upload', jsonParser, function(req, res) {
console.dir(req.body);
res.send(req.body.name);
});
app.get('/profile/:id/user/:name', function(req, res) {
console.dir(req.params);
res.send("You requested to see a profile with the name of " + req.params.name);
});
app.get('/ab?cd', function(req, res) {
res.send('/ab?cd');
})
app.listen(3000);
console.log('listening to port 3000');