Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active October 12, 2018 06:51
Show Gist options
  • Save ivankisyov/083c38e5b3cbbfd379c55327b39ce6c8 to your computer and use it in GitHub Desktop.
Save ivankisyov/083c38e5b3cbbfd379c55327b39ce6c8 to your computer and use it in GitHub Desktop.
Express

Express [Node.js]

Handling errors

// 404
app.use((req, res, next) => {
  let error = new Error("Route not found!");
  error.status = 404;
  next(error);
});

// all other errors
app.use((error, req, res, next) => {
  res.status(error.status || 500).json({
    message: error.message
  });
});

Multiple params

http://localhost:3000/api/posts/1988/10

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

result:

{
  "year": "1988",
  "month": "10"
}

Query string params

http://localhost:3000/api/articles?sortBy=name

app.get("/api/articles", (req, res) => {
  res.status(200).send(req.query);
});

result:

{
  "sortBy": "name"
}

Send headers with the response

res.header('x-auth-token', token).send('user created')

Retrieve request's header

const token = req.header('x-auth-token')

Useful middleware modules

app.use(helmet()); // needs to be installed first
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan("tiny")); // needs to be installed first
app.use(express.static("public")); // static files goes in public dir

Additional middleware modules:

http://expressjs.com/en/resources/middleware.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment