我试图创建类别到电子商务项目,然后它抛出一个错误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
我面对这个问题,然后我不能弄清楚发生了什么事,我的代码谢谢!
6条答案
按热度按时间hgncfbus1#
请确保您已经更改了Postman标题部分中的“Content-Type”。
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(单击文件而不是文本)
tyky79it3#
你也可以尝试下面的代码,我希望它能为你工作。
4ngedf3f4#
将
slug: { type: String, slug: "title"}
添加到模型中。zpf6vheq5#
我试着调试
slugify: string argument expected
的问题,发现在我的例子中,this
对象是{}
,所以它抛出了slugify: string argument expected
。尝试查找slugify方法中是否正确接收了所有值。代码片段
06odsfpq6#
再检查一遍你的路线,也许有一条行不通