express---1.入门

var express = require('express')
var app = express()
var bodyParser = require('body-parser');


// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

var host = "192.168.1.102"
var port = 8081

// 开启监听
var server = app.listen(port,host,function(){
    var host = server.address().address
    var port = server.address().port

    console.log('address === http://%s:%s',host,port)
})

// 0.设置静态目录,可以直接访问public目录下的资源文件
// http://127.0.0.1:8081/images/logo.png
app.use(express.static('public'))

//---------------------------------//
// 1.处理get请求
// request:对象表示 HTTP 请求,包含了请求查询字符串,参数,内容,HTTP 头部等属性
// response:对象表示 HTTP 响应,即在接收到请求时向客户端发送的 HTTP 响应数据。
app.get('/',function(req,res){
    console.log('主页 GET 请求')
    // 传送响应
    res.send('Hello World');
})

// 2.处理post请求
app.post('/',function(req,res){
    console.log('主页 POST 请求')
    res.send('Hello World')
})
//---------------------------------//

// 3.路由处理:决定了由谁(指定脚本)去响应客户端请求
app.get('/del_user',function(req,res){
    console.log('/del_user 响应DELETE请求')
    res.send('用户删除页面')
})

app.get('/list_user', function (req, res) {
    console.log("/list_user GET 请求");
    res.send('用户列表页面');
})

app.get('/ab*cd',function(req,res){
    console.log('/ab*cd GET 请求')
    res.send('正则匹配')
})

//---------------------------------//
// 4.处理参数
app.get('/index.html',function(req,res){
    // 传送指定路径的文件
    res.sendFile(__dirname + "/" + "index.htm")
})

// 处理get请求参数
app.get('/process_get',function(req,res){
    // 输出 JSON 格式
    var response = {
        // req.query:获取URL的查询参数串
        "first_name":req.query.first_name,
        "last_name":req.query.last_name
    };
    console.log(response);

    // 中文部分乱码的问题
    res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
    res.end(JSON.stringify(response));
})

// 处理post请求参数
app.post('/process_post', urlencodedParser, function (req, res) {
 
   // 输出 JSON 格式
    var response = {
        // 获得「请求主体」
        "first_name":req.body.first_name,
        "last_name":req.body.last_name
    };
   console.log(response);
   res.end(JSON.stringify(response));
})
//---------------------------------//
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值