简体   繁体   中英

Why is this error displaying 'Illegal arguments: undefined, string'?

I am building a simple node.js app. I build my backend api for user registration. I am trying to test it with postman and i am having this error 'Illegal arguments: undefined, string'. What could be responsible for this?. Relevant codes are supplied below

User Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema

const UserSchema = new Schema({

    userName: {
        type: String,
        required: true,
        unique: true

    },
    firstName: {
        type: String,
    },
    lastName: {
        type: String,
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    dateOfRegistration: {
        type: Date,
        default: Date.now
       
    },
    dateOfBirth: {
        type: Date,
    },
     userCategory: {
        type: String,
        default: 'workingClass'
       
    }

})
module.exports = mongoose.model('users', UserSchema)


controller

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('config');
const auth = require('../middleware/auth')
const { check, validationResult } = require('express-validator');
const User = require('../models/User');
const UserModel = require('../models/User');


// @route   POST api/users, Register a users; access   Public

router.post('/', [
    check('userName', 'Please add user name').not().isEmpty(),
    check('email', 'Please include a valid email').isEmail(),
    check('password', 'Please enter a password with six or more characters').isLength({ min: 5 })
    ],
  async (req, res) => {
    const errors = validationResult(req);
    if(!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    
    const  { userName, firstName, lastName, email, password, dateOfBirth, dateOfRegistration, userCategory } = req.body;

    try {
        let user = await User.findOne( { email });

        if (user) {
            return res.status(400).json({ msg: 'User already exist'})
        }
        
        user = new User({
            userName,
            firstName,
            lastName,
            email,
            password,
            dateOfBirth,
            dateOfRegistration,
            userCategory
        });

        const salt = await bcrypt.genSalt(10);

        user.password = await bcrypt.hash(password, salt);

        await user.save();

        
        const payload = {
            user: {
                id: user.id
            } 
        }

      
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error')  
    }
   }
  );

module.exports = router;

server.js

const express = require('express');
const mongoose = require('mongoose');
const path = require('path');

// api require routes
const users = require('./routes/users');
// const auth = require('./routes/auth');
// const students = require('./routes/studentsSub');
// const workers = require('./routes/workersSub');


const app = express();

// database connection
const connectDB = async () => {
    try {
        await mongoose.connect('mongodb+srv://nawill:usha0816@cluster0.77u0d.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', 
        {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            useFindAndModify: false  
        });
        console.log('MongoDB Connected ...')
    } catch (err) {
        console.error(err.message);
        process.exit(1);
    }
};
connectDB();

//Middleware
app.use(express.json({ extended: false }));
// app.get('/', (req, res) => res.json ({ msg: 'Hello node project'}));


//Routes
app.use('/api/users', users );
// app.use('/api/auth', auth );
// app.use('/api/students', students );
// app.use('/api/workers', workers );


//Start Server
app.listen(3000, ()=> console.log("Server started on 3000"))

The problem has been solved. Postman was sending the request as in 'text' format instead of 'JSON' format and as such the backend couldn't make sense of data. Every worked fine when changed the settings on my Postman from 'text' to 'JSON'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM