为了账号安全,请及时绑定邮箱和手机立即绑定

Building RESTful APIs with Express(Node.js)

标签:
Node.js

REST defines a set of conventions for creating HTTP services:

  • POST: to create a resource
  • PUT: to update it
  • GET: to read it
  • DELETE: to delete it

Express is a simple, minimalistic and lightweight framework for building web
servers.

// Build a web server
const express = require(‘express’);
const app = express();

// Creating a course
app.post(/api/courses’, (req, res) => {
// Create the course and return the course object
resn.send(course);
});

// Getting all the courses
app.get(/api/courses’, (req, res) => {
// To read query string parameters (?sortBy=name)
const sortBy = req.query.sortBy;

// Return the courses
res.send(courses);
});

// Getting a single course
app.get(/api/courses/:id’, (req, res) => {
const courseId = req.params.id;

// Lookup the course
// If not found, return 404
res.status(404).send(‘Course not found.);

// Else, return the course object
res.send(course);
});

// Updating a course
app.put(/api/courses/:id’, (req, res) => {
// If course not found, return 404, otherwise update it
// and return the updated object.
});

// Deleting a course
app.delete(/api/courses/:id’, (req, res) => {
// If course not found, return 404, otherwise delete it
// and return the deleted object.
});

// Listen on port 3000
app.listen(3000, () => console.log(‘Listening…’));
  • We use Nodemon to watch for changes in files and automatically restart the
    node process.
  • We can use environment variables to store various settings for an application. To
    read an environment variable, we use process.env.
// Reading the port from an environment variable
const port = process.env.PORT || 3000;
app.listen(port);
  • You should never trust data sent by the client. Always validate! Use Joi package
    to perform input validation.

  • A middleware function is a function that takes a request object and either
    terminates the request/response cycle or passes control to another middleware
    function.

  • Express has a few built-in middleware functions:

  • json(): to parse the body of requests with a JSON payload

  • urlencoded(): to parse the body of requests with URL-encoded payload

  • static(): to serve static files

  • You can create custom middleware for cross-cutting concerns, such as logging,
    authentication, etc.

// Custom middleware (applied on all routes)
app.use(function(req, res, next)) {
// …
next();
}
// Custom middleware (applied on routes starting with /api/admin)
app.use(/api/admin’, function(req, res, next)) {
// …
next();
}
  • We can detect the environment in which our Node application is running
    (development, production, etc) using process.env.NODE_ENV and
    app.get(‘env’).
  • The config package gives us an elegant way to store configuration settings for
    our applications.
  • We can use the debug package to add debugging information to an application.
    Prefer this approach to console.log() statements.
  • To return HTML markup to the client, use a templating engine. There are various
    templating engines available out there. Pug, EJS and Mustache are the most
    popular ones.
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
251
获赞与收藏
1274

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消