NodeJS 获取错误:slugify:需要字符串参数

jfgube3f  于 2023-06-05  发布在  Node.js
关注(0)|答案(6)|浏览(286)

我试图创建类别到电子商务项目,然后它抛出一个错误Postman - throws an error
这些是源代码
位置:电子商务后台\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}`)
    })

位置:电子商务后台\路由\类别. 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

我面对这个问题,然后我不能弄清楚发生了什么事,我的代码谢谢!

hgncfbus

hgncfbus1#

请确保您已经更改了Postman标题部分中的“Content-Type”。

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

avkwfej42#

我只是做下面的步骤:
1.从package.json删除slugify
1.重新安装slugify包:你会发现
发现了2个严重性较高的漏洞,请运行npm audit fix来修复它们,或运行npm audit以获取详细信息
1.运行npm audit fix
1.打开新窗口!从/api/admin/create复制令牌并将此令牌粘贴到新窗口中:体内/api/category/create
form-data:
name(在您的数据库中尚不存在)
categoryImage(单击文件而不是文本)

tyky79it

tyky79it3#

你也可以尝试下面的代码,我希望它能为你工作。

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

4ngedf3f4#

slug: { type: String, slug: "title"}添加到模型中。

zpf6vheq

zpf6vheq5#

我试着调试slugify: string argument expected的问题,发现在我的例子中,this对象是{},所以它抛出了slugify: string argument expected。尝试查找slugify方法中是否正确接收了所有值。
代码片段

Schema.pre('save', (next)=> {
  console.log(`pre hook is triggered ${this.name}`.silly);
  // this.set({ updatedAt: new Date() });
  this.slug = slugify(this.name,{lower:true})
  next()
})
06odsfpq

06odsfpq6#

再检查一遍你的路线,也许有一条行不通

相关问题