灵心如玉,守一生无惧|

SadicZhou

园龄:3年2个月粉丝:7关注:4

node08_01使用express创建最基本的服务器

Express:基于 Node.js 平台,快速、开放、极简的 Web 开发框架。
文档:https://www.expressjs.com.cn/
下载:$ npm install express --save
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//1.导入express
const express = require('express')
//2.创建web服务器
const app = express()
//4.监听客户端的GET和POST请求,并向客户端响应具体的内容
app.get('/user', (req, res) => {
    //调用express提供的res.send()方法,向客户端响应一个JSON对象
    res.send({ name: '小周', age: '23', sex: '男' })
})
app.post('/user', (req, res) => {
    //调用express提供的res.send()方法,向客户端响应一个其他类型数据
    res.send([{ name: '小明', age: '25', sex: '女' }, '请求成功'])
})
//3.启动web服务器
app.listen(80, () => {
    console.log('express server running at http://127.0.0.1'+'使用了nodemon')
})
app.get('/', (req, res) => {
    //通过req.query可以获取到客户端发送过来的查询参数
    //注意:默认情况下,req.query是一个空对象
    console.log(req.query)
    res.send(req.query)
})
 
//注意:这里的:id是一个动态的参数
app.get('/user/:id/:name', (req, res) => {
    //req.params是动态匹配到的URL参数,默认是空对象
    console.log(req.params)
    res.send(req.params)
     
})

  对上面的接口进行调用,验证结果是否正确:

1.get请求/user

 

 2.post请求user

 

 3.get请求/,入参:name:lisi,id:001

 

 4.携带url参数请求

 

 可以看到验证结果和代码都是一致的。这就是通过express搭建一个基本的服务器的流程。


本文作者:ZihangChu

本文链接:https://www.cnblogs.com/SadicZhou/p/16882742.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   SadicZhou  阅读(35)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 尚好的青春 孙燕姿
  2. 2 孙燕姿
  3. 3 克卜勒 孙燕姿
尚好的青春 - 孙燕姿
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.