如何在ExpressJS中使用axios?

时间:2018-12-19 07:49:37

标签: node.js express axios

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

4 个答案:

答案 0 :(得分:2)

您忘记回复客户了:

class ButtonWithProperty: UIButton {

    var isRead: Bool = false {
        didSet {
            setBadge()
        }
    }

    lazy var badgeView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 3
        view.backgroundColor = .red
        return view
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        addSubview(badgeView)
        badgeView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            badgeView.rightAnchor.constraint(equalTo: rightAnchor, constant: 3),
            badgeView.topAnchor.constraint(equalTo: topAnchor, constant: 3),
            badgeView.heightAnchor.constraint(equalToConstant: badgeView.layer.cornerRadius*2),
            badgeView.widthAnchor.constraint(equalToConstant: badgeView.layer.cornerRadius*2)
        ])

        setBadge()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setBadge() {
        badgeView.isHidden = isRead
    }

}

答案 1 :(得分:1)

  1. 由于axios已经具有catch块,因此您不必将axios调用包含在try...catch中。

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

您的代码应如下所示

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)
  }
})

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

            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;