簡體   English   中英

為什么此錯誤顯示“非法 arguments:未定義,字符串”?

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

我正在構建一個簡單的 node.js 應用程序。 我構建了我的后端 api 用於用戶注冊。 我正在嘗試使用 postman 對其進行測試,但出現此錯誤“非法 arguments:未定義,字符串”。 什么可以為此負責? 相關代碼如下

用戶模式

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;

服務器.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"))

問題已解決。 Postman 以“文本”格式而不是“JSON”格式發送請求,因此后端無法理解數據。 將我的 Postman 上的設置從“文本”更改為“JSON”時,一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM