可以使用node-fetch向本地主机发出发布请求,但无法使用Axios进行发布

时间:2018-11-16 09:38:47

标签: axios node-fetch

我尝试使用node-fetchaxios发出相同的帖子请求。

var fetch = require('node-fetch');
var axios = require('axios');

async function fetchTest(host, port, body) {
    const response = {
        successMessage: '',
        errorMessage: ''
    }

    try {
        const streamResponse = await fetch(`${host}:${port}`, {
            method: 'post',
            body: JSON.stringify(body)
        })
        const jsonResponse = await streamResponse.json()
        response.successMessage = jsonResponse;
    } catch (error) {
        response.errorMessage = error;
    }

    return response;
}

async function axiosTest(host, port, body) {
    const response = {
        successMessage: '',
        errorMessage: ''
    }

    try {
        const jsonResponse = await axios({
            method: 'post',
            url: `${host}:${port}`, 
            data: body
        })
        response.successMessage = jsonResponse;
    } catch (error) {
        response.errorMessage = error;
    }

    return response;
}

async function test() {
    console.log(await fetchTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
    console.log(await axiosTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));

}

test();

使用node-fetch发出的请求运行良好。用axios发出的请求返回(用...编辑的IP地址)错误:

{ successMessage: '',
  errorMessage:
   { Error: connect ECONNREFUSED ...:80
       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
     errno: 'ECONNREFUSED',
     code: 'ECONNREFUSED',
     syscall: 'connect',
     address: '...',
     port: 80,
     config:
      { adapter: [Function: httpAdapter],
        transformRequest: [Object],
        transformResponse: [Object],
        timeout: 0,
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        headers: [Object],
        method: 'post',
        url: 'http://127.0.0.1:8801',
        data: '{"type":"request","cmd":"devices"}' },
     request:
      Writable {
        _writableState: [WritableState],
        writable: true,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _options: [Object],
        _redirectCount: 1,
        _redirects: [],
        _requestBodyLength: 39,
        _requestBodyBuffers: [],
        _onNativeResponse: [Function],
        _currentRequest: [ClientRequest],
        _currentUrl: 'http://.../',
        _isRedirect: true },
     response: undefined } }

可能是什么原因?我在做错什么吗?

已编辑,评论中要求提供更多信息:

如果我注释掉axios请求,则node-fetch请求也会失败。

node-fetch请求返回:

{
    cmd: 'devices',
    payload: { devices: [Array] },
    type: 'response' },
}

由于我将结果包装在响应对象中,因此console.log看起来像

{ 
    successMessage:
    { 
        cmd: 'devices',
        payload: { devices: [Array] },
        type: 'response' 
    },
    errorMessage: '' 
}

0 个答案:

没有答案