Ad

Axios Call From Node API To PHP Server Leads To Socket Hangup

- 1 answer

I have created an API in Nodejs using Express.

On calling the Node API it reads a file and sends it to a PHP server which is deployed in Apache.The response is received from the PHP server and is sent back to the caller of my Node API. The first time when my Node API is hit it returns the correct result.From the second hit onwards 'Socket Hang up' is the error that i am getting.

var express = require('express')
var app = express()
const axios = require('axios');
var path = require('path');
const FormData = require('form-data'); 
const form = new FormData();
var fs = require('fs');
var dir = './tmp';

app.get('/file', function(request, responses) {

  new Promise((resolve , reject)=>{
    form.append('file',fs.createReadStream(dir+'/FileCreated.txt'));
    resolve(form);
  }).then(form => {
    console.log('Sending file to the PHP ');
    let url = 'http://121.115.158.12/upload.php';  
    axios({
                    method: 'post',
                    url: url, 
                    // timeout : 3000,
                    data: form,
                    headers: {
                        'content-type': `multipart/form-data;boundary=${form._boundary} `,//
                        }  
                })
                .then(function (response) {
                    console.log(response.status);

                    responses.send({status:response.status , data: response.data});
                    responses.end();
                })
                .catch(function (error) {
                    console.log(error);                  
                    responses.send({status:error.status , data: error.Error});
                    responses.end();
                });               

                request.on('end', function() {
                  console.log('close');
                });

     })

})

The error that I receive from second Axios hit onwards.

{ Error: socket hang up
    at createHangUpError (_http_client.js:323:15)
    at Socket.socketOnEnd (_http_client.js:426:23)
    at Socket.emit (events.js:194:15)
    at endReadableNT (_stream_readable.js:1103:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  code: 'ECONNRESET',
  config:
   { url: 'http://121.115.158.12/upload.php/',
     method: 'post',
     data:
      FormData {
        _overheadLength: 314,
        _valueLength: 0,
        _valuesToMeasure: [Array],
        writable: false,
        readable: true,
        dataSize: 0,
        maxDataSize: 2097152,
        pauseStreams: true,
        _released: true,
        _streams: [Array],
        _currentStream: null,
        _insideLoop: false,
        _pendingNext: false,
        _boundary: '--------------------------691559357280045881646354',
        _events: [Object],
        _eventsCount: 1 },
     headers:
      { Accept: 'application/json, text/plain, */*',
        'Content-Type':
         'multipart/form-data;boundary=--------------------------691559357280045881646354 ',
        'User-Agent': 'axios/0.19.0' },
     transformRequest: [ [Function: transformRequest] ],
     transformResponse: [ [Function: transformResponse] ],
     timeout: 0,
     adapter: [Function: httpAdapter],
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus] },
  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:
      [Object: null prototype] {
        response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { protocol: 'http:',
        maxRedirects: 21,
        maxBodyLength: 10485760,
        path: '/upload.php/',
        method: 'POST',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: '121.115.158.12',
        port: null,
        nativeProtocols: [Object],
        pathname: '/upload.php/' },
     _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: true,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _headerSent: false,
        socket: [Socket],
        connection: [Socket],
        _header: null,
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        path: '/upload.php/',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'http://121.115.158.12/upload.php/' },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function] }

Observations:

1)The first hit to PHP server(deployed in Apache) is properly logged in the log file of Apache but from the second hit onwards there are no logs in Apache probably telling me that the Axios request is even not reaching Apache?

2)I have built one more Node API just to check if I hit that API then will i get the socket hangup error, but this API runs each time.Even if I am getting socket hangup on the above API, this one runs perfectly.

app.get('/random', function(request, responses) {
 console.log(responses);
  responses.send('Just to check');
})
Ad

Answer

Still was not able to find the reason for the issue. I found a roundabout and used shell script to hit the PHP server using Shell.js .

This solution worked fine.

Ad
source: stackoverflow.com
Ad