Nodejs快速上手D2--ExpressJS

1.初次尝试express

javascript 复制代码
// 1.导入express模块
const express = require('express');
// 2.创建应用对象
const app=express();
// 3.创建路由
app.get('/home',(req,res)=>{
  res.end('hello express');
})
// 4.监听端口,启动服务
app.listen(9000,()=>{
  console.log('服务启动成功 端口9000监听中...');
})

2.express路由

路由组成:请求方法、路径、回调函数

javascript 复制代码
// 1.导入express模块
const express = require('express');
// 2.创建应用对象
const app=express();
// 3.创建路由
app.get('/home',(req,res)=>{
  res.end('hello express');
})
// 默认请求路由为'/'
app.get('/',(req,res)=>{
  res.end('home');
})
// 直接在地址栏敲回车则会报错,因为地址栏访问为get请求
app.post('/login',(req,res)=>{
  res.end('login');
})
app.all('/test',(req,res)=>{
  res.end('test');
})
// 当以上请求都不符合时,会执行以下路由(404处理)
app.use((req,res)=>{
  res.status(404).end('404 not found');
})
// 4.监听端口,启动服务
app.listen(9000,()=>{
  console.log('服务启动成功 端口9000监听中...');
})

使用post的方式进行请求(因为url直接访问都是发送get请求,所以定义一个表单进行post请求的发起)

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form method="post" action="http://localhost:9000/login">
    <button>登录</button>
    </form>
</body>
</html>

结果:

使用了通配符进行404的处理(当出现不没定义过的路由规则时)

3.获取请求报文参数

javascript 复制代码
const express = require('express');

const app=express();

app.get('/request',(req,res)=>{
  console.log(req.method);
  console.log(req.url);
  console.log(req.httpVersion);
  console.log(req.headers);

// 提取路径
console.log(req.path);
// 获取query参数
console.log(req.query);
// 获取请求的ip地址
console.log(req.ip);

  res.end('express request');
  })
app.listen(9000,()=>{
  console.log('express server running at http://127.0.0.1');
});

路径传入参数

结果

4.express获取路径参数

场景:京东或者淘宝等电商平台传入类似http://baidu/1288995.html 的商品信息,后端需要获取params(1288995),通过params返回对应的内容给前端

javascript 复制代码
const express = require('express');

const app=express();

// 此处填入一个id的占位符
app.get('/:id.html',(req,res)=>{
  // 获取路径参数id(要和占位符的名称一致)
console.log(req.params.id);
res.setHeader('Content-Type','text/plain; charset=utf-8');
res.end('商品详情');
  })
app.listen(9000,()=>{
  console.log('express server running at http://127.0.0.1');
});

4.1 练习:通过不同路由参数进行歌手信息查询

使用json定义几个歌手信息

json 复制代码
{
  "singers":[
    {
      "singer_name":"dua lipa",
      "singer_id":1,
      "singer_age":"25"
    },
    {
      "singer_name":"ariana grande",
      "singer_id":2,
      "singer_age":"50"
    },
    {
      "singer_name":"pinkpantheress",
      "singer_id":3,
      "singer_age":"20"
    },
    {
      "singer_name":"chappell roan",
      "singer_id":4,
      "singer_age":"20"
    },
    {
      "singer_name":"lana del rey",
      "singer_id":5,
      "singer_age":"32"
    },
    {
      "singer_name":"lorde",
      "singer_id":6,
      "singer_age":"60"
    }
  ]
}

思路:

使用require模块进行json文件导入

填入占位符+使用request.params属性获取用户填入的歌手id

使用find方法和内部回调函数获取对应的id,通过id返回对应的歌手信息(item)

在end中套入html骨架进行渲染

javascript 复制代码
const express = require('express');
// 导入json文件
const {singers}=require('./singer.json');
console.log(singers);
const app=express();

// 此处填入一个id的占位符
app.get('/singer/:singer_id.html',(req,res)=>{
// 获取路由参数
let {singer_id}=req.params;
// 在数组中寻找对应id的数据
res.setHeader('Content-Type','text/html; charset=utf-8');
let result=singers.find((item)=>{
  // id本来为字符串,这里需要使用Number进行强制类型转换
  if(item.singer_id===Number(singer_id)){
    return item;
  }
});

console.log(result);
// 将对应歌手信息渲染到html中
if(!result){
  res.statusCode=404;
  res.end('<h1>404</h1>');
}
  res.end(`<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>${result.singer_name}</h1>
  <p>歌手ID:${result.singer_id}</p>
  <p>歌手年龄:${result.singer_age}</p>
</body>
</html>`);
  })
app.listen(9000,()=>{
  console.log('express server running at http://127.0.0.1');
});

结果:

相关推荐
用户69371750013842 小时前
2026,程序员的时代拐点到了
android·前端·后端
惜鸟2 小时前
从源码看 pi 的上下文管理:原始数据永久保留,模型视角按需裁剪
后端
量化分析码农2 小时前
【Python量化策略评估体系 #05】极端行情扛得住吗?2008/2015/2020 三场景压力测试
后端
十年Java程序媛2 小时前
Java 接口和抽象类对比|Java8 新特性,抛弃老旧八股,正确选型
java·spring boot·后端
IT_陈寒2 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
用户8356290780512 小时前
使用 Python 对 Excel 工作表进行排序
后端·python
程序员cxuan2 小时前
腾讯又来一王炸,开源版 WorkBuddy 太夯了!
人工智能·后端·程序员
用户8356290780513 小时前
使用 Python 合并 PowerPoint 演示文稿
后端·python
掘金者阿豪3 小时前
数据同步软件技术实践:从异构数据库迁移到实时数据流转,解析电科金仓KFS架构设计
后端
ServBay3 小时前
不会写代码,如何搭建自己的 AI 自动化工作流
后端·aigc·ai编程