我是 Node js 新手。我在我的应用程序中使用了express和sequelize。
这是我的路由器功能。
router.post('/add-merchant', [
check('name').not().isEmpty(),
check('city').not().isEmpty(),
check('state').not().isEmpty(),
check('country').not().isEmpty(),
], (req, res, next) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.json({ errors: errors.array()});
}
var merchant = merchantService.addMerchant(req);
return res.json(merchant)
} catch (error) {
return res.json({"status": "error", "message": error.message})
}
});
我创建了名为merchantService.js的文件
我在merchantService.js中添加了用于插入数据的代码并尝试了这样的
var merchant = merchantService.addMerchant(req);
但我无法从商家服务中获取任何数据。这是我的商家服务代码
var models = require("../models");
var merchantService = {
addMerchant: (req) => {
models.merchants.create(req.body).then((merchant) => {
return merchant.dataValues
});
}
}
module.exports = merchantService;
我找不到问题。请帮助任何人解决这个问题。
提前致谢
最佳答案
您正在以同步方式管理异步任务,但它不起作用。
您应该以这种方式更改您的请求处理程序:
router.post('/add-merchant', [
check('name').not().isEmpty(),
check('city').not().isEmpty(),
check('state').not().isEmpty(),
check('country').not().isEmpty(),
], (req, res, next) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.json({ errors: errors.array() });
}
merchantService.addMerchant(req).then((merchant)=>{
res.json(merchant)
})
} catch (error) {
return res.json({ "status": "error", "message": error.message })
}
});
并像这样修复您的商家服务(请参阅返回
值以启动 promise 链):
const merchantService = {
addMerchant: (req) => {
return models.merchants.create(req.body)
.then((merchant) => {
return merchant.dataValues
});
}
}
module.exports = merchantService;
关于node.js - 如何在Node.js中使用服务层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54604954/