Cannot POST /user/register

10,390

Your error below is in the app.js.

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
/Users/wailin/Documents/Projects/meanauthapp/app.js:41
app.post('/', (req,res))

AFAIK req, res are properties from express.Router(). But you just call this in your router-files but not in your app.js

Share:
10,390
WaiLin
Author by

WaiLin

Currently Vue.js developer. Interested in Web Technologies, especially in Front-end related stuffs. Also I'm a Linux hobbyist, my current favourite distro is Manjaro.

Updated on June 05, 2022

Comments

  • WaiLin
    WaiLin almost 2 years

    I'm trying to learn MEAN stack with a tutorial and I'm sticking in some point when I tried to test post method with POSTMAN I've searched and tried many ways and can't find the answer yet.

    Codes are : app.js

    const express = require('express'),
        path = require('path'),
        bodyParser = require('body-parser'),
        cors = require('cors'),
        passport = require('passport'),
        mongoose = require('mongoose');
    
    const users = require('./routes/users'),
        config = require('./config/database');
    
    //Connect to database
    mongoose.connect(config.database);
    //On Connection
    mongoose.connection.on('connected', () => {
        console.log('Connected to database : ' + config.database);
    });
    //On Error
    mongoose.connection.on('error', (err) => {
        console.log('Database error : ' + err);
    });
    
    const app = express();
    
    //Port number
    const port = 3000;
    
    //Cors Middleware
    app.use(cors());
    
    app.use(express.static(path.join(__dirname, 'public')));
    
    //Body Parser Middleware
    app.use(bodyParser.json());
    
    app.use('/users', users);
    
    //Index route
    app.get('/', (req, res) => {
        res.send('Invalid response');
    });
    app.post('/', (req, res) => {
        res.send('Invalid response');
    })
    
    //Start Server
    app.listen(port, () => {
        console.log('Server stated with port : ' + port);
    });
    

    Route code: users.js

    const express = require('express'),
        passport = require('passport'),
        jwt = require('jsonwebtoken'),
        router = express.Router();
    
    const User = require('../models/user');
    
    //Register
    router.post('/register', (req, res, next) => {
        let newUser = new User({
            name: req.body.name,
            email: req.body.email,
            username: req.body.username,
            passowrd: req.body.passowrd
        });
    
        User.addUser(newUser, (err, user) => {
            if (err) {
                res.json({ success: false, msg: 'Failed to register user!' });
            } else {
                res.json({ success: true, msg: 'User Registered' });
            }
        });
    });
    
    module.exports = router;
    

    Model code: user.js

    const mongoose = require('mongoose'),
        bcrypt = require('bcryptjs'),
        config = require('../config/database');
    
    //User Schema
    const userSchema = mongoose.Schema({
        name: {
            type: String
        },
        email: {
            type: String,
            required: true
        },
        username: {
            type: String,
            required: true
        },
        passowrd: {
            type: String,
            required: true
        }
    });
    
    module.exports.addUser = function (newUser, callback) {
        bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(newUser.passowrd, salt, (err, hash) => {
                if (err) throw err;
                newUser.passowrd = hash;
                newUser.save(callback);
            });
        });
    }
    
    const User = module.exports = mongoose.model('User', userSchema);
    

    POSTMAN config :

    Method : POST

    URL http://localhost:3000/users/register

    Header key: Content-Type , value: application/json

    Body
    {
        "name": "Wai Lin Aung",
        "email": "[email protected]",
        "username": "Wai Lin",
        "passowrd": "123456"
    }
    

    POSTMAN output:

    HTML

    Cannot POST /user/register

    JSON : Unexpected '<'

    Terminal Log:

    [nodemon] restarting due to changes...
    [nodemon] starting `node app.js`
    /Users/wailin/Documents/Projects/meanauthapp/app.js:41
    app.post('/', (req,res))
                ^
    
    ReferenceError: req is not defined
        at Object.<anonymous> (/Users/wailin/Documents/Projects/meanauthapp/app.js:41:16)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
        at Module.runMain (module.js:604:10)
        at run (bootstrap_node.js:393:7)
        at startup (bootstrap_node.js:150:9)
        at bootstrap_node.js:508:3
    

    Updated Log:

    [nodemon] restarting due to changes...
    [nodemon] starting `node app.js`
    Server stated with port : 3000
    Connected to database : mongodb://localhost:/27017/meanauth
    TypeError: User.addUser is not a function
        at router.post (/Users/wailin/Documents/Projects/meanauthapp/routes/users.js:17:10)
        at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
        at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/route.js:137:13)
        at Route.dispatch (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/route.js:112:3)
        at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
        at /Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:281:22
        at Function.process_params (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:335:12)
        at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:275:10)
        at Function.handle (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:174:3)
        at router (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:47:12)
        at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
        at trim_prefix (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:317:13)
        at /Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:284:7
        at Function.process_params (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:335:12)
        at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:275:10)
        at /Users/wailin/Documents/Projects/meanauthapp/node_modules/body-parser/lib/read.js:129:5