NodeJS入门 0x5 NodeWeb程序(2)搭建一个 RESTful Web 服务

本文详细介绍了使用Express框架搭建RESTful Web服务的过程,包括创建、读取、更新和删除文章的API实现,以及如何配置消息解析器处理POST请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

搭建一个 RESTful Web 服务

    新建项目 

     添加消息解析器


搭建一个 RESTful Web 服务

    设计 RESTful 服务时,要想好需要哪些操作,并将它们映射到 Express 里的路由上。就此例而言,需要实现保存文章、获取文章、获取包含所有文章的列表和删除不再需要的文章这几个功能。分别对应下面这些路由:

  • POST /articles——创建新文章;
  • GET /articles/:id——获取指定文章;
  • GET /articles——获取所有文章;
  • DELETE /articles/:id——删除指定文章。

    新建项目 

mkdir listing3_1
cd listing3_1
npm init -fy
npm install --save express@4.12.4
const express = require('express');
const app = express();
const articles = [{title:'Example'}];

app.set('port',process.env.PORT||3000);

app.get('/articles',(req,res,next)=>{//获取所有文章
    res.send(articles);
});

app.post('/articles',(req,res,next)=>{//创建一篇文章
    res.send('OK');
});

app.get('/articles/:id',(req,res,next)=>{//获取指定文章
    const id = req.params.id;
    console.log('Fetching:',id);
    res.send(articles[id]);
});

app.delete('/articles/:id',(req,res,next)=>{//删除指定文章
    const id = req.params.id;
    console.log('Deleting:',id);
    delete articles[id];
    res.send({message:'Deleted'});
});

app.listen(app.get('port'),()=>{
    console.log('App started on port',app.get('port'));
});

module.exports = app;

     添加消息解析器

    处理 POST 请求需要消息体解析。消息体解析器知道如何接收 MIME-encoded(多用途互联网邮件扩展) POST 请求消息的主体部分,并将其转换成代码可用的数据。一般来说,它给出的是易于处理的 JSON 数据。只要网站上有涉及提交表单的请求,服务器端就肯定会有一个消息体解析器来参与这个请求的处理。

//完成post部分
const express = require('express');
const app = express();
const articles = [{title:'Example'}];
const bodyParser = require('body-parser');

app.set('port',process.env.PORT||3000);

app.use(bodyParser.json());//支持编码为JSON的请求体
app.use(bodyParser.urlencoded({extended:true}));//支持编码为表的请求体

app.get('/articles',(req,res,next)=>{//获取所有文章
    res.send(articles);
});

app.post('/articles',(req,res,next)=>{//创建一篇文章
    const article = {title:req.body.title};
    articles.push(article);
    res.send(article);
});

app.get('/articles/:id',(req,res,next)=>{//获取指定文章
    const id = req.params.id;
    console.log('Fetching:',id);
    res.send(articles[id]);
});

app.delete('/articles/:id',(req,res,next)=>{//删除指定文章
    const id = req.params.id;
    console.log('Deleting:',id);
    delete articles[id];
    res.send({message:'Deleted'});
});

app.listen(app.get('port'),()=>{
    console.log('App started on port',app.get('port'));
});

module.exports = app;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值