前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Express.js Tutorial: Build RESTful APIs with Node and Express | Mosh

Express.js Tutorial: Build RESTful APIs with Node and Express | Mosh

作者头像
ccf19881030
发布2020-05-18 17:22:12
1.6K0
发布2020-05-18 17:22:12
举报
文章被收录于专栏:ccf19881030的博客

Express.js Tutorial: Build RESTful APIs with Node and Express | Mosh

在Youtube上看到Mosh的一篇关于使用Node和Express构建RESTful APIs的示例,对应的视频地址是:Express.js Tutorial: Build RESTful APIs with Node and Express | Mosh,作者Mosh的Youtube地址是:Programming with Mosh

TABLE OF CONTENT:

00:49 What are RESTful APIs 06:48 Introducing Express 09:09 Your First Web Server 14:57 Nodemon 16:29 Environment Variables 19:44 Route Parameters 25:22 Handling HTTP GET Requests 30:09 Handling HTTP POST Requests 33:53 Calling APIs using Postman 36:03 Input Validation 44:03 Handling HTTP PUT Requests 52:33 Handling HTTP DELETE Requests

http://programmingwithmosh.com

创建程序

首先保证在自己的系统下安装了Node.js程序,然后安装配置node和npm、cnpm等 然后使用cnpm或npm安装express和joi依赖,

代码语言:javascript
复制
cnpm install express joi

对应的代码如下:

代码语言:javascript
复制
const Joi = require('joi');
const express = require('express');
const app = express();

app.use(express.json());

// 课程列表数组
const courses =[
  { id: 1, name: '语文' },
  { id: 2, name: '数学' },
  { id: 3, name: '英语' },
  { id: 4, name: '计算机组成原理' },
  { id: 5, name: '数据结构' },
  { id: 6, name: '操作系统' },
  { id: 7, name: '编译原理' }
]

app.get('/', (req, res) => {
  res.send('Hello World');
})

// 获取所有的课程信息
app.get('/api/courses', (req, res) => {
  res.send(courses);
});

// 提交一门课程
app.post('/api/courses', (req, res) => {
  const { error } = validateCourse(req.body); // result.error
  if (error) {
    return res.status(400).send(error.details[0].message);
  }

  // 在提交课程前,对课程名进行校验,若课程名为空或者小于3个字符,则返回
  // if (!req.body.name || req.body.name.length < 3) {
  //   // 400 Bad Request
  //   res.status(400).send('Name is required and should be minimum 3 characters.');
  //   return;
  // }

  // 创建一个课程对象
  const course = {
    id: courses.length + 1,
    name: req.body.name
  };
  // 向课程列表数组中添加一个新项
  courses.push(course);
  res.send(course);
});

// 根据课程id查询某个课程
app.get('/api/courses/:id', (req, res) => {
  const course = courses.find(c => c.id === parseInt(req.params.id));
  if (!course) { // 404
    return res.status(404).send('The course with the given ID was not found!');
  }
  res.send(course);
});

// 根据课程id更新某门课程
app.put('/api/courses/:id', (req, res) => {
  // Look up the course
  // If not existing, return 404
  const course = courses.find(c => c.id === parseInt(req.params.id));
  if (!course) { // 404
    return res.status(404).send('The course with the given ID was not found!');
  }
  // Validate
  // If invalid, return 400 - Bad request
  const { error } = validateCourse(req.body); // result.error
  if (error) {
    return res.status(400).send(error.details[0].message);
  }
  // Update course
  // Return the updated course
  course.name = req.body.name;
  res.send(course);
});

// 根据课程id删除某门课程
app.delete('/api/courses/:id', (req, res) => {
  // Look up the course
  // Not existing, return 404
  const course = courses.find(c => c.id === parseInt(req.params.id));
  if (!course) { // 404
    return res.status(404).send('The course with the given ID was not found!');
  }

  // Delete
  const index = courses.indexOf(course);
  courses.splice(index, 1);

  // Return the same course
  res.send(course);
})

// app.get('/api/posts/:year/:month', (req, res) => {
//   res.send(req.params);
//   //res.send(req.query);
// });

// app.post()
// app.put()
// app.delete()
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`App Listening on port ${port}...`);
});

function validateCourse(course) {
  const schema = {
    name: Joi.string().min(3).required()
  };

  return Joi.validate(course, schema);
}

关于http接口测试工具,可以使用Postman或者在VSCode中使用rest-client插件进行测试,或者使用curl工具进行测试。

不过需要注意的是,在npm官网上作者说joi包已经被废弃了,建议使用@hapi/joi

This package has been deprecated Author message:

This module has moved and is now available at @hapi/joi. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.

参考资料

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/05/09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Express.js Tutorial: Build RESTful APIs with Node and Express | Mosh
    • TABLE OF CONTENT:
      • 创建程序
      • 参考资料
      相关产品与服务
      Serverless HTTP 服务
      Serverless HTTP 服务基于腾讯云 API 网关 和 Web Cloud Function(以下简称“Web Function”)建站云函数(云函数的一种类型)的产品能力,可以支持各种类型的 HTTP 服务开发,实现了 Serverless 与 Web 服务最优雅的结合。用户可以快速构建 Web 原生框架,把本地的 Express、Koa、Nextjs、Nuxtjs 等框架项目快速迁移到云端,同时也支持 Wordpress、Discuz Q 等现有应用模版一键快速创建。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档