简体   繁体   English

为什么此错误显示“非法 arguments:未定义,字符串”?

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

I am building a simple node.js app.我正在构建一个简单的 node.js 应用程序。 I build my backend api for user registration.我构建了我的后端 api 用于用户注册。 I am trying to test it with postman and i am having this error 'Illegal arguments: undefined, string'.我正在尝试使用 postman 对其进行测试,但出现此错误“非法 arguments:未定义,字符串”。 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 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服务器.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. Postman 以“文本”格式而不是“JSON”格式发送请求,因此后端无法理解数据。 Every worked fine when changed the settings on my Postman from 'text' to 'JSON'.将我的 Postman 上的设置从“文本”更改为“JSON”时,一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:非法参数:未定义,字符串 - Error: Illegal arguments: undefined, string _async 处的“UnhandledPromiseRejectionWarning:错误:非法 arguments:未定义,字符串” - "UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, string" at _async 非法 arguments:未定义,字符串 - Illegal arguments: undefined, string “错误:非法 arguments:字符串,未定义”并在节点 JS 中停止服务器 - "Error: Illegal arguments: string, undefined" and stop server in node JS 尝试使用 postman API 发布数据时出现错误“非法 arguments:字符串,未定义” - Having an error " Illegal arguments: string, undefined " while trying to post data using postman API 为什么我使用简单的哈希函数出现非法参数错误? - Why I got Illegal arguments error with simple hash function? 为什么带有参数的返回函数未定义? - Why return function with arguments is undefined? Bcrypt 错误:错误:非法回调:NodeJS 中的字符串 - Bcrypt error: Error: Illegal callback: string in NodeJS 当我使用javascript时为什么会出现“非法字符语法错误未终止的字符串文字” - Why I get “Illegal Character Syntax Error Unterminated String Literal” when I using javascript 为什么{…undefined}不是错误,但是…undefined是错误 - Why {…undefined} is not an error, but …undefined is an error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM