首页 > 解决方案 > 如何在 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;

我找不到问题。请帮助任何人解决此问题。

提前致谢

标签: node.jsexpresssequelize.js

解决方案


您正在以同步方式管理异步任务,但它不起作用。

您应该以这种方式更改您的请求处理程序:

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;

推荐阅读