app.js:
/*
1.cmd--- cd 到项目里面
2.npm init --yes / npm init (创建package.json)
3.安装express
npm install express --save / cnpm install express --save
4.引入express使用
var express=require('express');
var app=new express(); //new可以省略 var app=express();
app.get('',function(req,res){
})
*/
var express=require('express'); /*引入*/
var app=new express(); //实例化 new可以省略 var app=express();
//路由前面必须加 "/" http://localhost:3001
app.get('/',function(req,res){
res.send('你好express'); // send()是end()的封装,只能调用一次, 封装了状态码、请求头等。
});
//动态路由 aid是接收到的参数名 http://localhost:3001/index/123
app.get('/index/:aid',function(req,res){
console.log(req.params); // { aid: '123' }
var aid=req.params.aid;
res.send('index页面--'+aid);
});
//获取get传值 http://localhost:3001/product?aid=123&cid=456
app.get('/product',function(req,res){
console.log(req.query); //获取get传值 { aid: '123', cid: '456' }
res.send('product--'+req.query.aid+'---'+req.query.cid);
});
// app.post('/dopost',function(req,res){}); // app.all('',function(){}); all表示get和post请求。 路由路径不区分大小写。
app.listen(3001,'127.0.0.1');