1

我尝试使用node-fetchand发出相同的发布请求axios

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: '' 
}
4

0 回答 0