19

Trying to understand what's going on with my GET request. I set this up on the backend using node.js. I first thought I was using the wrong .env, url, username, and password... but when I checked on Postman, Basic Auth seemed to be getting the JSON data without any issues. Am I using AXIOS wrong?

Here's my GET request:

let customers;
try {
    let user_res = await axios({
        method: "GET",
        url: "api._____.com/customers",
        auth: {
            username: process.env.USERNAME,
            password: process.env.PASSWORD
        }
    });
    customers = user_res.data;
    console.log(customers);
} catch (err) {
    const error = new HttpError(
        "API failed, please try again.",
        500
    );
    return next(error);
}

ERROR Log:

API_NAME error Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1137:16) {
    errno: -61,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 80,
    config: {
        url: 'api.___.com/customers',
        method: 'get',
        headers: {
        Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.19.1'
        },
        auth: {
        username: '___',
        password: '___'
        },
        transformRequest: [ [Function: transformRequest] ],
        transformResponse: [ [Function: transformResponse] ],
        timeout: 0,
        adapter: [Function: httpAdapter],
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        data: undefined
    },
    request: <ref *1> 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,
        afterWriteTickInfo: null,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        autoDestroy: false,
        errored: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object]
        },
        writable: true,
        _events: [Object: null prototype] {
        response: [Function: handleResponse],
        error: [Function: handleRequestError]
        },
        _eventsCount: 2,
        _maxListeners: undefined,
        _options: {
        protocol: 'http:',
        maxRedirects: 21,
        maxBodyLength: 10485760,
        path: 'api.___.com/customers',
        method: 'GET',
        headers: [Object],
        agent: undefined,
        agents: [Object],
        auth: '___',
        hostname: null,
        port: null,
        nativeProtocols: [Object],
        pathname: 'api.___.com/customers'
        },
        _redirectCount: 0,
        _redirects: [],
        _requestBodyLength: 0,
        _requestBodyBuffers: [],
        _onNativeResponse: [Function (anonymous)],
        _currentRequest: ClientRequest {
        _events: [Object: null prototype],
        _eventsCount: 6,
        _maxListeners: undefined,
        outputData: [],
        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: [Socket],
        _header: 'GET api.___.com/customers HTTP/1.1\r\n' +
            'Accept: application/json, text/plain, */*\r\n' +
            'User-Agent: axios/0.19.1\r\n' +
            'Host: localhost\r\n' +
            'Authorization: Basic ___==\r\n' +
            'Connection: close\r\n' +
            '\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        method: 'GET',
        maxHeaderSize: undefined,
        insecureHTTPParser: undefined,
        path: 'api.___.com/customers',
        _ended: false,
        res: null,
        aborted: false,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        reusedSocket: false,
        _redirectable: [Circular *1],
        [Symbol(kCapture)]: false,
        [Symbol(kNeedDrain)]: false,
        [Symbol(corked)]: 0,
        [Symbol(kOutHeaders)]: [Object: null prototype]
        },
        _currentUrl: 'http:api.___.com/customers',
        [Symbol(kCapture)]: false
    },
    response: undefined,
    isAxiosError: true,
    toJSON: [Function (anonymous)]
}
Etep
  • 2,721
  • 4
  • 17
  • 28

5 Answers5

12

I understand that your url is defined like: api.___.com/customers, however you should define it like http://api.___.com/customers or https://api.___.com/customers if you have it.

pedrohcms
  • 195
  • 1
  • 7
1

Well, 127.0.0.1 means that it's being refused by your local computer (127.0.0.1) on port 80. Maybe you need to add an exception to that port your local machine? Another thing to look out for is CORS issues if your server itself, but typically that is met with an error detailing that to be the case.

Abe
  • 421
  • 3
  • 11
  • So I tried running "sudo netstat -tulpn | grep LISTEN" on my terminal, but didn't see port 80 being used – Etep Mar 07 '20 at 00:31
  • 1
    Try this command my guy `sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT` – Abe Mar 07 '20 at 00:40
  • I have a mac so I don't think I can use iptables. Would pf work? If so, what would be the equivalent? Lastly, should I just create a separate stack question and have you answer that and then link it to this question? – Etep Mar 09 '20 at 17:48
  • It would be more clear to edit your current question for future readers! – Abe Mar 09 '20 at 19:50
  • 1
    Another note, have you tried running the script as root? Or even changing which port you're hosting the API you're trying to self reference on? So for instance, instead of 80, host the API on 8080 temporarily for testing purposes. Edit: [This link to another article](https://serverfault.com/questions/742364/port-80-connection-refused-how-to-fix-on-mac-osx) may help you as well in opening port 80 on Mac – Abe Mar 09 '20 at 19:52
0

For my case i found a solution : I deploy my API project using localhost:8000, and it sounds like localhost is not directly 127.0.0.1 because of my host.conf file. So i deploy my lumen app on 127.0.0.1:8000 then my expressJs connection worked

0

I set the URL with HTTP and the problem is solved!

axios.post('http://localhost:8080/user.json', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
0

Nuxt 3 user here. For me it was because I set up sitemap creation before all plugins etc. were loaded; so axios.defaults.baseurl caused an error. I changed the variable to https://api.blahblah.com and the error disappeared.

gnegis
  • 31
  • 3