I am practicing with APIs and have one working, but all of the endpoints are in the default app.js file. My question is, how can I move endpoints to different files/folders to organize my code?
HERE IS AN EXAMPLE:
App.js
app.get('/contact', (req, res)=>{
res.status(200).send('CONTACT')
})
app.get('/about', (req, res)=>{
res.status(200).send('ABOUT')
})
How can I move my '/about' endpoint to another file called 'about.js' and have it still be accessible as an endpoint? All express tutorials that I look up only use the app.js file and never create multiple files.
CodePudding user response:
You can use the below code for your reference.
app.js
const express = require('express')
const about = require('./about');
const contact = require('./contact');
const app = express()
const port = 3000
app.use('/contact', contact);
app.use('/about', about);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
about.js
const express = require('express')
const app = express()
module.exports = app.get('/', (req, res)=>{
res.status(200).send('ABOUT From about.js file')
});
contact.js
const express = require('express')
const app = express()
module.exports = app.get('/', (req, res)=>{
res.status(200).send('CONTACT From contact.js file')
});
CodePudding user response:
You can use this below file structure
app.js
var admin = require('./routes/admin.js');
app.use('/admin',admin)
admin.js
var adminController = require('../Controllers/admin/index.js');
admin.post('/register', function (req, res, next) {
adminController.insertAdmin(req.headers, req.body).then(function (insertAdmin) {
res.status(200).send(insertAdmin);
}, function (err) {
res.status(400).send(err);
}).catch(function (e) {
console.log('500 error', err);
res.status(500).send(e);
})
});