Home > Enterprise >  How can I separate an API into diferent files? (routes) Node.js MySQL
How can I separate an API into diferent files? (routes) Node.js MySQL

Time:10-26

I'm new here. I wanted to know how can I "separate" mi app.js (API) into several files, mainly for the routes but also the connections too if it is posible. I tried several video tutorials but none of them worked, so here is my code (only file), I want the routes in a separated file (routes.js):

const mysql = require('mysql')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3050
const app = express()

app.use(bodyParser.json())

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'shop'
})

app.get('/', (req, res) => {
    res.send('Welcome to my API!')
})

//ROUTES!!!

app.get('/customers', (req, res) => {
    const sql = 'SELECT * FROM customers'
    connection.query(sql, (err, results) => {
        if (err) throw err
        if (results.length > 0) {
            res.json(results)
        } else {
            res.send('No results!')
        }
    })
})

app.get('/customers/:id', (req, res) => {
    const { id } = req.params
    const sql = `SELECT * FROM customers WHERE id = ${id}`
    connection.query(sql, (err, result) => {
        if (err) throw err
        if (result.length > 0) {
            res.json(result)
        } else {
            res.send('No result!')
        }
    })
})

connection.connect(error => {
    if (error) throw error
    console.log('Database server running!')
})
app.listen(PORT, () => console.log(`Server running on ${PORT}`))

CodePudding user response:

create n new file ApiRouter.js and add following code in it.
const express = require("express");
const router = express.Router();

router.get('/customers', (req, res) => {
    const sql = 'SELECT * FROM customers'
    connection.query(sql, (err, results) => {
        if (err) throw err
        if (results.length > 0) {
            res.json(results)
        } else {
            res.send('No results!')
        }
    })
})

router.get('/customers/:id', (req, res) => {
    const { id } = req.params
    const sql = `SELECT * FROM customers WHERE id = ${id}`
    connection.query(sql, (err, result) => {
        if (err) throw err
        if (result.length > 0) {
            res.json(result)
        } else {
            res.send('No result!')
        }
    })
})
module.exports = router;


//now go to app.js file and add these line of codes below 
app.use(bodyParser.json())

const route = require('./path/ApiRouter.js'); // require from file
app.use('/', route);

CodePudding user response:

You can use express.Router object to define some routes in separe file. Then export the router object and do app.use('/api/some-sub-path', router)

You can read more about Router here https://expressjs.com/en/guide/routing.html

Also I advice you to read this article https://dev.to/santypk4/bulletproof-node-js-project-architecture-4epf

CodePudding user response:

create router in another file by 
const router = require('express').Router;
router.get();
and now in app.js use router as 
app.use('/' , router);
  • Related