开发者问题收集

如何在 ExpressJS 中使用 axios?

2018-12-19
75698

我希望能够使用我的 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.
3个回答

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

尝试 .then(response => res.json(response.data))

Alex G
2018-12-19
  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)
  }
})
Dinesh Pandiyan
2018-12-19
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)
Manoj M
2021-09-01