Home > Net >  Router doesn't return json what wrong?
Router doesn't return json what wrong?

Time:04-04

This code don't give a response, where is trouble? index.js:

const express = require('express')
const mongoose = require('mongoose')
const authRouter = require('./authRouter') //import of router.
const PORT = process.env.PORT || 3000


const app = express()
app.use(express.json()) //to get server to parse
app.use('/auth', authRouter)


const start = async () =>{
    try{
        await mongoose.connect('mongodb srv://*****:*****@cluster0.lwems.mongodb.net/myFirstDatabase?retryWrites=true&w=majority')
        app.listen(PORT, ()=> console.log('Server started on 3000'))
    } catch(e){
        console.log(e)
    }
}

start()

authRouter.js

const Router = require('express')
const controller = require('./authController')
const router = new Router()  //create an object


router.post('/registration', controller.registration)
router.post('/login', controller.login)
router.post('/users', controller.getUsers) //for different access

module.exports = router

authController.js

class authController{
    async registration(req,res) {
        try {
            
        } catch (e) {
            console.log(e)
        }
    }
    async login(req, res) {
        try {
        } catch (e) {
            console.log(e)
        }
    }
    async getUsers(req, res) {
        try {
            res.json("HEY")
        } catch (e) {
            console.log(e)
        }
    }

}

module.exports = new authController()

when i do request from browser it returns: Cannot GET /auth/users

I don't understand where is my mistake. all done in accordance with example.

CodePudding user response:

Cannot GET /auth/users

Try changing request method from post to get in AuthRouter.js

router.post('/registration', controller.registration)
router.post('/login', controller.login)
router.get('/users', controller.getUsers)

CodePudding user response:

The problem is you are not returning the res.json()

Please do -

async getUsers(req, res) {
    try {
        return res.json("HEY");
    } catch (e) {
        console.log(e)
        return res.json({"result":"failed", "error": e});
    }
}

and it would work ;)

  • Related