简体   繁体   English

从 Node API 到 PHP 服务器的 Axios 调用导致套接字挂断

[英]Axios call from Node API to PHP server leads to socket hangup

I have created an API in Nodejs using Express.我使用 Express 在 Nodejs 中创建了一个 API。

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.在调用 Node API 时,它会读取一个文件并将其发送到部署在 Apache 中的 PHP 服务器。从 PHP 服务器接收响应并将其发送回我的 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.第一次命中我的节点 API 时,它返回正确的结果。从第二次命中开始,“套接字挂断”是我得到的错误。

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.我从第二个 Axios 收到的错误开始出现。

{ 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? 1)第一次命中 PHP 服务器(部署在 Apache 中)已正确记录在 Apache 的日志文件中,但从第二次命中开始,Apache 中没有日志可能告诉我 Axios 请求甚至没有到达 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. 2)我又构建了一个 Node API 只是为了检查我是否点击了该 API,然后我会收到套接字挂断错误,但是这个 API每次都运行。即使我在上述 API 上遇到套接字挂断,这个 API 也能完美运行。

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

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 . 我找到了一个回旋处,并使用Shell脚本使用Shell.js命中PHP服务器。

This solution worked fine. 此解决方案效果很好。

i am facing the same issue.... i have same process to send the data.我面临同样的问题......我有相同的过程来发送数据。 node server fetching and sending(post) data using axios to php server which is hosted in apache server.节点服务器使用 axios 获取和发送(发布)数据到托管在 apache 服务器中的 php 服务器。

please suggest me the sample of code请给我建议代码示例

I am using this to post the data我正在使用它来发布数据

const newInstance = axios.create({ url: http://in.truemagic-media.com/import_data/${channelId} , method: 'post', headers: { "USERKEY": "TYapJkTR", "PASSWORD": "z85qTWnA" }, timeout: 1800000, httpAgent: new http.Agent({ keepAlive: true }) }); const newInstance = axios.create({ url: http://in.truemagic-media.com/import_data/${channelId} , method: 'post', headers: { "USERKEY": "TYapJkTR", "PASSWORD": "z85qTWnA" }, timeout: 1800000, httpAgent: new http.Agent({ keepAlive: true }) });

let result = await newInstance.post(`http://in.truemagic-media.com/import_data/${channelId}`,dataTOSend)
return result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM