V
V
Viktor2020-04-28 12:29:43
Node.js
Viktor, 2020-04-28 12:29:43

Why body-parser only works in app.js?

I figured it was my mistake.
The connection to the database must be moved to a separate file and connected in the file with the request.
The bodyparser has nothing to do with it, the request to the database did not pass.
----------------------------
Hello.
The situation is this, I include a bodyparser in app.js

const express = require('express')
const mongoose = require('mongoose')
const pg = require('pg')
const bodyParser = require('body-parser')
const authRoutes = require('./routes/auth')
const analyticsRoutes = require('./routes/analytics')
const categoryRoutes = require('./routes/category')
const orderRoutes = require('./routes/order')
const positionRoutes = require('./routes/position')
const keys = require('./lib/config/keys')
const app = express()

const pgdb = new pg.Pool(keys.pgPool)
pgdb.connect()
  .then(() => console.log('PG Connected'))
  .catch(error => console.log(error))

app.use(require('morgan')('dev'))
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(require('cors')())

app.use('/api/auth', authRoutes)

module.exports = app


and I try to write a post request, which I also write in app.js

app.post('/register', async (req, res) => {
    const obj = req.body
    const queryReg = 'INSERT INTO public.users(email, password) VALUES ($1, $2)'
    await pgdb.query(queryReg, [obj.email, obj.password])
    res.send('ok')
  }


The request is processed. But I want to put routers and controllers in separate files.
I create a folder of routes, I include the route in app.js the content of the route

const authRoutes = require('./routes/auth')


const express = require('express')
const controller = require('../controllers/auth')
const router = express.Router()
 
 
router.post('/login', controller.login)
router.post('/register', controller.register)
 
module.exports = router


for the test in the controller I prescribe res, I see the result, the route works. I register a request and it does not work, it does not parse the json object that I pass to it, but the same object parses the contents of the controller
along the route from app.js

module.exports.register = async (req, res) => {
    const obj = req.body
    const queryReg = 'INSERT INTO public.users(email, password) VALUES ($1, $2)'
    await pgdb.query(queryReg, [obj.email, obj.password])
    res.send('ok')
  }


Why does the bodyparser only parse in the main file?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question