连接到redis的api在curl调用时返回值,但在axios调用时不返回值

cuxqih21  于 2021-06-07  发布在  Redis
关注(0)|答案(1)|浏览(437)

我设置了一个expressjsapi来服务来自前端的请求,并将其连接到我的redis数据库。一个端点接收请求url(get request)中指定的参数,并返回一个数字。当我使用axios或node fetch访问这个端点时,它返回null,如果键不存在,node redis就会返回null。当我用curl和chrome点击这个端点时,它返回正确的数字。其他端点功能正常。为什么会这样?
服务器代码:

  1. router.get("/api/:id/bal", async (req, res) => {
  2. let id = req.params.id;
  3. await client.get(id, (err, response) => {
  4. if (err) throw err;
  5. res.send(response);
  6. });
  7. });

axios呼叫:

  1. axios.get(`http://localhost:4000/api/${id}/bal`)
  2. .then((response) => {
  3. console.log(response.data);
  4. })

curl 呼叫:

  1. curl http://localhost:4000/api/id/bal -i

(在这两种情况下,id均替换为真实的帐户id)

beq87vna

beq87vna1#

不确定这是否有帮助,但是,混合回调和 async/await 不推荐。根据您使用的redis库的不同,可能会有所不同,但我假设您使用的是 node-redis ,这在默认情况下不是promisified,因此您必须坚持回调:

  1. router.get("/api/:id/bal", (req, res, next) => {
  2. let id = req.params.id;
  3. client.get(id, (err, response) => {
  4. if (err) return next(err); // do not throw inside callbacks !
  5. // if you do nobody catch the error
  6. // you have to pass it to `next` to let express handle it.
  7. console.log('redis response:', response); // added a log so we can check the value
  8. res.send(response); // maybe more need to be done here, proper formating ?
  9. });
  10. });

或者你可以自己承诺redis(你需要node 8+和express 5+):

  1. const { promisify } = require("util");
  2. const getAsync = promisify(client.get).bind(client);
  3. router.get("/api/:id/bal", async (req, res) => {
  4. let id = req.params.id;
  5. const response = await getAsync(id);
  6. console.log('redis response:', response)
  7. res.send(response);
  8. });

自从我们使用 async/await express将捕获并处理错误,而不需要使用回调和 next !
现在只需检查日志,如果失败,可以尝试用json发送 res.json(response) ?

展开查看全部

相关问题