得到一个错误:slugify:需要字符串参数

Posted

技术标签:

【中文标题】得到一个错误:slugify:需要字符串参数【英文标题】:Getting an Error: slugify: string argument expected 【发布时间】:2021-05-10 17:07:16 【问题描述】:

我尝试为电子商务项目创建类别,然后引发错误 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`)
    )

位置: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

位置:电子商务后端\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)

位置:电子商务后端\控制器\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

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

【问题讨论】:

【参考方案1】:

确保您已更改邮递员标题部分中的“内容类型”。

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

【讨论】:

【参考方案2】:

我只做以下步骤:

    package.json删除slugify

    重新安装 slugify 包:你会看到

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

    运行npm audit fix

    打开新窗口!在邮递员和 从 /api/admin/create 复制令牌并将此令牌粘贴到新窗口中:/api/category/create in body ,

    表单数据:

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

    categoryImage(点击文件而非文本)

【讨论】:

以上是关于得到一个错误:slugify:需要字符串参数的主要内容,如果未能解决你的问题,请参考以下文章

php PHP的简单slugify功能。为传递的字符串创建一个slug,同时考虑国际字符。

C# 中的 Slugify 和字符转写

PHP 在PHP中使用Slugify字符串

在PHP中对字符串进行Slugify

django slugify 俄语字符串 [重复]

如何在保持 UTF-8 字母的同时进行 slugify [重复]