nodejs之express框架一

文档手册: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');

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值