【问题标题】:How do I use axios within ExpressJS?如何在 ExpressJS 中使用 axios?
【发布时间】:2019-05-19 16:17:04
【问题描述】:

我希望能够使用我的 React 应用程序向我的服务器发出 GET 请求,这假设提示我的服务器向外部 API 发出 GET 请求。 我正在使用 axios 并尝试使用请求,但两者都给了我 ERRTIMEOUT。 正如我在前端应用程序上尝试过的那样,请求肯定有效,并且请求有效

const express = require("express");
const axios = require("axios");
const router = express.Router();

router.get("/test", (req, res, next) => {
    console.log("'/test' call");
    axios.get("https://api.neoscan.io/api/main_net/v1/get_all_nodes")
       .then(data => res.json(data))
       .catch(err => res.secn(err));
})

module.exports = router;`

错误代码

GGWP! { Error: connect ETIMEDOUT 104.25.167.105:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  address: '104.25.167.105',
  port: 443,
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.18.0' },
     method: 'get',
     url: 'https://api.neoscan.io/api/main_net/v1/get_all_nodes',
     data: undefined },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     _events:
      { response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { protocol: 'https:',
        maxRedirects: 21,
        maxBodyLength: 10485760,
        path: '/api/main_net/v1/get_all_nodes',
        method: 'get',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: 'api.neoscan.io',
        port: null,
        nativeProtocols: [Object],
        pathname: '/api/main_net/v1/get_all_nodes' },
     _redirectCount: 0,
     _redirects: [],
     _requestBodyLength: 0,
     _requestBodyBuffers: [],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [TLSSocket],
        connection: [TLSSocket],
        _header:
         'GET /api/main_net/v1/get_all_nodes HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.18.0\r\nHost: api.neoscan.io\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/api/main_net/v1/get_all_nodes',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'https://api.neoscan.io/api/main_net/v1/get_all_nodes' },
  response: undefined }

这是我在响应后得到的附加错误代码

(node:35220) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at stringify (.\new-viewer\node_modules\express\lib\response.js:1119:12)
    at ServerResponse.json (.\new-viewer\node_modules\express\lib\response.js:260:14)
    at ServerResponse.send (.\new-viewer\node_modules\express\lib\response.js:158:21)
    at axios.get.then.catch.err (.\new-viewer\server\api\index.js:45:27)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:40496) UnhandledPromiseRejectionWarning: TypeError: res.error is not a function
    at axios.get.then.catch.err (.r\server\api\index.js:36:17)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:40496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:40496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

【问题讨论】:

  • 您在关闭const axios = require("axios); 时缺少" 执行此操作const axios = require("axios")
  • @KuchBhi 我的错。在我的代码中是正确的。一定是这里不小心删掉了
  • Yap 意识到,否则您将不会遇到该错误。

标签: node.js express axios


【解决方案1】:

Axios 会向您返回整个响应,因此如果您尝试发送此响应,则会收到循环依赖错误。 所以在.then(data =&gt; res.json(data)),数据实际上就是响应。

试试.then(response =&gt; res.json(response.data))

【讨论】:

    【解决方案2】:
    1. 您不必将您的 axios 调用包含在 try...catch 中,因为 axios 已经有一个 catch 块。

    2. 当 axios 从 API 调用获得响应或 axios 在 API 调用期间捕获错误时,您的 express 处理程序必须发回响应。

    你的代码应该是这样的

    router.get("/test", (req, res, next) => {
      console.log("'/test' call");
      axios.get("https://api.neoscan.io/api/main_net/v1/get_all_nodes")
        .then(data => res.json(data))
        .catch(err => next(err));
    })
    

    如果你喜欢async...await,你可以这样写代码

    router.get("/test", async (req, res, next) => {
      console.log("'/test' call");
      try {
        const res = await axios.get("https://api.neoscan.io/api/main_net/v1/get_all_nodes");
        res.json(data);
      }
      catch (err) {
        next(err)
      }
    })
    

    【讨论】:

    • @c-chavez 我们为什么要等待res.json(data)
    • 嗨@DineshPandiyan 我已经厌倦了你的第一种方法,但我仍然遇到错误。我已经用底部的错误更新了最初的帖子。它们都是 UnhandledPromiseRejectionWarnings。而且我仍然无法收到请求
    • @mLjH 我已经更新了我的答案。看起来您得到的是来自 axios 调用的响应,但将其转换为 json 是问题所在。尝试将错误发送到next(err) 回调,看看发生了什么。
    • 它返回给我Error: connect ETIMEDOUT 104.25.168.105:443 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)
    • 这几乎就像您的防火墙阻止了该地址。我可以从我的位置点击 URL 并获得响应。
    【解决方案3】:

    你忘记回复客户了:

     try{
        axios.get("https://api.neoscan.io/api/main_net/v1/get_all_nodes")
               .then(data => res.status(200).send(data))
               .catch(err => res.send(err));
     }
     catch(err){
        console.error("GG", err);
     }
    

    【讨论】:

    • 我已经尝试过了,但仍然遇到同样的错误。除了现在,它还告诉我其他的东西,比如 UnhandledPromiseRejectiongWarning: TypeError: Converting circular structure to JSONUnhandledPromiseRejectiongWarning: Unhandled promise rejection.... 不是用 .catch() 处理的
    • 检查你的catch块,你得到了其他错误。
    【解决方案4】:
                Modifying the previous answer ,
                try using response.data , then send it back to handler will solve the issue 
                try the snippet below
                const express = require('express');
                const axios=require("axios");
                const { response } = require('express')
                const router = express.Router();
    
                router.get("/",async (req, res, next) => {
                
                try {
                    const response = await axios.get("https://api.neoscan.io/api/main_net/v1/get_all_nodes");
                    console.log(response.data);
                    res.send(response.data);
                }
                catch (err) {
                    next(err)
                }
                })
    
    
                module.exports=router;
    

    【讨论】:

      【解决方案5】:
      const express = require('express')
      const axios = require('axios')
      const app = express()
      
      app.get("/", async (req, res) => {
          try {
              const response = await axios.get("https://jsonplaceholder.typicode.com/posts")
              res.json(response.data)
          }
          catch (err) {
              console.log(err)
          }
      })
      
      app.get('*', (req, res) => {
          res.status(500).json({ message: "error" })
      })
      
      app.listen(3001)
      

      【讨论】:

      • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
      猜你喜欢
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 2018-06-29
      • 2021-03-04
      • 2023-04-01
      相关资源
      最近更新 更多