Axios和Express:在Get请求中发送参数会将一个空的params对象发送到后端

时间:2020-03-16 14:36:25

标签: javascript express xmlhttprequest axios sequelize.js

这是 Axios请求

API.get("api/client/getClientByPK", { params: { id: 22 } });

这是 Express路由器

router.get("/getClientByPK", function(req, res) {
  logger.info("req.params", JSON.stringify(req.params));
  clientServices.getClientByPK(req.params.id, res);
});

getClientByPk

var getClientByPK = function(clientPk, res) {
  models.client
    .findByPk(clientPk)
    .then(clientFound => {
      logger.debug("clientPk", clientPk);
      logger.info("clientFound", JSON.stringify(clientFound));
      if (clientFound != null) {
        res.status(200).json(clientFound);
      } else {
        res.status(404).json({ error: "ClientNotFound" });
      }
    })
    .catch(error => {
      logger.error(error);
      res.status(400).json(error);
    });
};

这是日志结果

2020-03-16T15:31:10+0100 <info> client_routes.js:12  req.params + {}
2020-03-16T15:31:10+0100 <debug> ClientServices.js:21  clientPk + 
2020-03-16T15:31:10+0100 <info> ClientServices.js:22  clientFound + null

我已经使用 POSTMAN 测试了后端,并且它运行良好。因此,我相信问题在于 AXIOS请求
PS:我在SO上仅找到一个答案,表明我使用数据而不是参数,但结果仍然相同。

1 个答案:

答案 0 :(得分:2)

Axios发送params对象作为查询参数。

您应该通过req.query而不是req.params来访问查询参数