Rest API with Express.JS
Build your API with Express.JS
Contents
To include packages/files
Include packages: packages are from package.json
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => res.send('Profile route'));
const jwt = require('jsonwebtoken');
Inlucde route/file:
|
|
File return
|
|
Try catch
|
|
Build Express API:
Hierarchy
|
|
Notes regarding REST API
-
Requests are third party requests sent to our sever(such as Postman)
-
Router.post/get/put/delete: it is how we handle incoming requests ( requests sent to our server)
1
router.post/get/put/delete('/', auth, async (req, res) => { do some response here});
-
Express.Router() use req,res to handle requests
1 2 3 4 5 6
req: contains POST request JSON body const {name, email, password} = req.body res: is whatever info the server sends back res.status(500).send('Server error'); res.status(400).json({errors: [{msg: 'User already exists'}]}); res.json({ msg: 'User deleted' });
More about REST API
POST:
- Requester sends info and data to a server
- POST request has a body (JSON) and a header (Content-Type, application/json , x-auth-token)
GET:
- DON’T have a body When a request is sent to our sever’s route, our server responds a message back (router.get(’/’, (req, res) => res.send(‘Profile route’));)
- Can have a header (x-auth-token)
PUT:
- Work like a POST, have body & header. But it meanly used to update a resource
Delete:
- Delete a resource in DB, usually require a x-auth-token in the header