node.js - 如何在 node js 中使用服务层
问题描述
我是 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})
}
});
我创建了一个名为 MercerService.js 的文件
我已经添加了用于在 MercerService.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 })
}
});
并像这样修复您的商家服务(查看return
值以启动承诺链):
const merchantService = {
addMerchant: (req) => {
return models.merchants.create(req.body)
.then((merchant) => {
return merchant.dataValues
});
}
}
module.exports = merchantService;
推荐阅读
- python - 如何从python列表中消除具有某些字符或短语的元素?
- javascript - 如何通过 javascript 中的嵌套子对象来分隔数组?
- python - 如何使用熊猫创建包含 NaN 的单独数据框
- javascript - 尝试使用 HTML/JavaScript 为游戏制作 HP 条
- c++ - 如何以不同的方式编写 reinterpret_cast<>
- html - 将特定行的 CSS 网格 2 列拆分为 3 列
- sql-server - 如何根据 SQL Server 中的 xQuery 的 XML 文件属性将值插入表中?
- matlab - 在 MATLAB 中将大图像写入 PDF
- java - 通过 java 8 lambda 更新 hashmap 中的对象
- uipopovercontroller - 更改 iOS 13 UIPopoverPresentationController 模糊和阴影量?