Getting an Error: slugify: string argument expected

Getting an Error: slugify: string argument expected

我尝试为电子商务项目创建类别然后它抛出错误 Postman - throws an error

这些是源代码

位置:ecommerce-backend\index.js

    const express = require('express')
    const env = require('dotenv')
    const app = express()
    const mongoose = require('mongoose')


    //routes
    const authRoutes = require('./routes/auth')
    const adminRoutes = require('./routes/admin/auth')
    const categoryRoutes = require('./routes/category')
    const productRoutes = require('./routes/product')
    const cartRoutes = require('./routes/cart')
    //environment variable or you can say constants
    env.config()

    //mongodb connection
    mongoose.connect(
        `mongodb+srv://${process.env.MONGO_DB_USERS}:${process.env.MONGO_DB_PASSWORD}@cluster0.nglbc.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`, 
        {
            useNewUrlParser: true, 
            useUnifiedTopology: true,
            useCreateIndex: true
        }
    ).then(() => {
        console.log('Database connected')
    });

    app.use(express.json())
    app.use('/api', authRoutes)
    app.use('/api', adminRoutes)
    app.use('/api', categoryRoutes)
    app.use('/api', cartRoutes)
    app.use('/api', productRoutes)

    app.listen(process.env.PORT, () => {
        console.log(`Server is running on port ${process.env.PORT}`)
    })

位置:ecommerce-backend\routes\category.js

    const express = require('express')
    const { requireSignin, adminMiddleware } = require('../common-middleware')
    const { addCategory,getCategories } = require('../controller/category')
    const router = express.Router()
    const path = require('path')
    const shortid = require('shortid')
    const multer = require('multer')

    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
          cb(null, path.join(path.dirname(__dirname), 'uploads'))
        },
        filename: function (req, file, cb) {
          cb(null, shortid.generate() + '-' + file.originalname)
        }
      })

    const upload = multer({ storage })

    router.post('/category/create',requireSignin, adminMiddleware,upload.single('categoryImage'), addCategory)
    router.get('/category/getcategory', getCategories)

    module.exports = router

位置:ecommerce-backend\models\category.js

    const mongoose = require('mongoose')
    const categorySchema = new mongoose.Schema({

        name: {
            type: String,
            required: true,
            trim: true
        },
        slug: {
            type: String,
            required: true,
            unique: true
        },
        categoryImage: {
            type: String,
        },
        parentId: {
            type: String
        }

    }, { timestamps: true})

    module.exports = mongoose.model('Category',categorySchema)

位置:ecommerce-backend\controller\category.js

const Category = require('../models/category')
const slugify = require('slugify')

function createCategories(categories, parentId = null){

    const categoryList = []
    let category
    if(parentId == null){
        category = categories.filter(cat => cat.parentId == undefined)
    }else{
        category = categories.filter(cat => cat.parentId == parentId)
    }

    for(let cate of category){
        categoryList.push({
            _id: cate._id,
            name: cate.name,
            slug: cate.slug,
            children: createCategories(categories,cate._id)
        })
    }

    return categoryList
}

exports.addCategory = (req, res) => {

    const categoryObj = {
        name: req.body.name,
        slug: slugify(req.body.name)
    }

    if(req.file){
            categoryObj.categoryImage = process.env.API + '/public/'+ req.file.filename
    }

    if(req.body.parentId){
        categoryObj.parentId = req.body.parentId
    }

    const cat = new Category(categoryObj)
    cat.save((error,category) => {
        if(error) return res.status(400).json({ error})
        if(category){
            return res.status(201).json({ category})
        }
    })
}

exports.getCategories = (req,res) => {
    Category.find({})
    .exec((error, categories) => {
        if(error) return res.status(400).json({error})

        if(categories){

            const categoryList = createCategories(categories)

            res.status(200).json({categoryList})
        }
    })
}

这是我在电子商务后端的 .env 文件\ .env

PORT = 2000
MONGO_DB_USERS = mrzombit
MONGO_DB_PASSWORD = ********
MONGO_DB_DATABASE = ecommerce
JWT_SECRET = MERNSECRET
API = http://localhost:2000

我遇到了这个问题然后我无法弄清楚我的代码发生了什么 谢谢!

确保您已更改邮递员 header 部分中的 'Content-Type'。

Content-Type: multipart/form-data; boundary=<calculated when request is sent>

我只做以下步骤:

  1. package.json

    中删除 slugify
  2. 重新安装 slugify 包:你会看到

    发现 2 个高危漏洞 运行 npm audit fix 修复它们,或 npm audit 了解详情

  3. 运行 npm audit fix

  4. 开新window!在邮递员和 从 /api/admin/create 复制令牌并将此令牌粘贴到新的 window: /api/category/create in body ,

    表单数据:

    名称(您的数据库中尚不存在)

    categoryImage(点击文件而非文本)

您也可以尝试使用以下代码,希望对您有用。

**slug: slugify(toString(req.body.name))**