首页 > 解决方案 > GET 请求适用于 cUrl 但不适用于 axios

问题描述

我正在尝试在 Axios 中设置请求。该请求与 cUrl 完美配合:

curl 'https://www.nseindia.com/api/quote-equity?symbol=COALINDIA' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36' -H 'Cookie: any' --compressed

但是我不能让它与 Axios 一起工作(在同一台服务器上)。这是我在 Node 中的请求:

var axiosOptions = { 
      method: 'GET',
      url: 'https://www.nseindia.com/api/quote-equity?symbol=COALINDIA',
      responseType: 'arraybuffer',
      timeout: 30000,
      headers: { 
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
            Cookie: 'any' 
      } 
}

await axios(axiosOptions)

它等待超时发送以下异常

Error: timeout of 30000ms exceeded
    at createError (/var/www/api/node_modules/axios/lib/core/createError.js:16:15)
    at Timeout.handleRequestTimeout [as _onTimeout] (/var/www/api/node_modules/axios/lib/adapters/http.js:217:16)
    at listOnTimeout (timers.js:327:15)
    at processTimers (timers.js:271:5)
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 30000,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
'User-Agent':
 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36',
Cookie: 'any' },
     method: 'get',
     url: 'https://www.nseindia.com/api/quote-equity?symbol=COALINDIA',
     responseType: 'arraybuffer',
     data: undefined },
  code: 'ECONNABORTED',
  request:
   Writable {
     _writableState:
      WritableState {
objectMode: false,
highWaterMark: 16384,

...

_header:
 'GET /api/quote-equity?symbol=COALINDIA HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36\r\nCookie: any\r\nHost: www.nseindia.com\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/api/quote-equity?symbol=COALINDIA',
_ended: false,
res: null,
...

我在 Axios 中做错了什么?

标签: javascriptnode.jscurlaxios

解决方案


我不知道你的代码到底有什么问题,但是这个更简单的版本在 node.js v12.13.1 中对我来说很好,所以你可以切换到这种使用形式axios

const axios = require('axios');

axios.get('https://www.nseindia.com/api/quote-equity?symbol=COALINDIA').then(result => {
    console.log(result.data);
}).catch(err => {
    console.log(err.code);
});

推荐阅读