Today we see how to create api endpoints and add them to the router.
We try to keep everything structured and clean. It's a good practice to keep everything readable.
Now we have below 2 steps for today.
Create api end points in the server file (server.js),
Create route for the different api endpoints.
Creating API endpoints
In the below code we created api endpoints and add required file to it. Now it is important to know that app.use()
is use to access any functionality or file written in any other folder.
const express = require('express')
const connectDB = require('./config/db');
const app = express();
connectDB();
const PORT = process.env.PORT || 5000;
//API endpoints
app.use('/api/auth', require('./routes/api/auth'));
app.use('/api/posts', require('./routes/api/posts'));
app.use('/api/profile', require('./routes/api/profile'));
app.use('/api/users', require('./routes/api/users'));
app.get('/', (req, res) => res.send('API Test'))
app.listen(PORT, () => {
console.log(`Server is running at ${PORT}`)
})
Creating route for api endpoints
Routes are nothing but different page of application having different component in it to work individually upon calling to their respective api.
Now create a folder name route within this folder create another folder name api and then create all the files accordingly.
As you can see below I have files as [auth, users, profile and posts].
You can just copy paste the below code in all the files
const express = require('express')
const route = express.Router();
//@route GET api/users
//@desc Test users
//@access public
route.get('/', (req, res) => res.send('Users route'));
module.exports = route;
You can check if APIs working or not on browser or use postman.
I am using postman and using port 5000.
Top comments (0)