代码之家  ›  专栏  ›  技术社区  ›  Yaron Idan

axios post请求挂起在有效请求上

  •  0
  • Yaron Idan  · 技术社区  · 6 年前

    我正在nodejs应用程序中使用axios向其他服务发送请求。
    当我发送请求并得到5xx或4xx错误代码响应时,Axios会很好地处理该请求并将错误返回给客户端。
    当请求结构良好时,它只是挂起,axios发送的承诺永远不会解决,让客户端无限期挂起等待响应。
    我不知道是什么导致只有有效请求挂起,或者如何进一步调试。
    到目前为止我试过的东西-

    • 使用postman发送请求(失败的和有效的)-它们按预期返回错误代码和ok代码。
    • 在vscode中调试节点进程,我可以看到axios正在无限期地内部循环,等待承诺的解决,但我还没有理解是什么阻止了承诺的解决。
    • Axios版本有点过时,所以我尝试过更新它,但这会产生新问题,所以我决定将其拨回原始版本。

    有关应用程序版本的一些信息,以备不时之需-

    • 节点版本-v9.11.1
    • Axios版本-0.9.1

    Axios请求片段,出于安全原因进行了编辑-

    const Router = require('express').Router;
    const router = Router();
    const axios = require('axios').create({
        baseURL: 'https://some-service.com'
    });
    
    const auth-handler = require('auth-handler');
    
    router.post('/', (req, res) => {
        auth-handler.getToken('token-name')
            .then(token => {
                const body = {
                    subject: "subject",
                    body: "body"
                };
    
                const options = {
                    headers: {
                        'Authorization': 'Bearer ' + token,
                        'Content-Type': 'application/json'
                    }
                };
                return axios.post('/'+req.body.route+'/endpoint?foo=bar', body, options);
            })
            .then(response => res.status(response.status).send(response.data))
            .catch(error => {
                console.error(error);
                res.status(error.status).send(error.data);
            });
    });
    0 回复  |  直到 6 年前
        1
  •  0
  •   Yaron Idan    6 年前

    答案是,axios已经按照预期解决了承诺,只是在我的程序的客户端没有任何指示,只有错误在表单中被正确指示。

    我添加了2xx响应的指示,现在一切都好了。