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

b4lqfgs4  于 2022-11-23  发布在  iOS
关注(0)|答案(3)|浏览(191)

我已经使用Express在Nodejs中创建了一个API。
在调用Node API时,它读取一个文件并将其发送到部署在Apache中的PHP服务器。从PHP服务器接收响应并将其发送回Node API的调用方。第一次命中Node API时,它返回正确的结果。从**第二次命中开始,“Socket Hang up”**是我得到的错误。

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');
                });

     })

})

我收到的错误,从第二个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] }

观察结果:
1)对PHP服务器(部署在Apache中)的第一次命中正确地记录在Apache的日志文件中,但从第二次命中开始,Apache中就没有日志了,这可能告诉我Axios请求甚至没有到达Apache?
2)我已经构建了一个节点API,只是为了检查如果我命中该API,我会得到套接字挂起错误,但这个API每次都运行。即使我在上面的API上得到套接字挂起,这个API也能完美运行。

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

nfg76nw01#

仍然无法找到问题的原因。我找到了一个迂回,并使用shell脚本使用Shell.js命中PHP服务器。
此解决方案工作正常。

ef1yzkbh

ef1yzkbh2#

我也面临着同样的问题....我有同样的过程来发送数据。节点服务器使用axios获取和发送(post)数据到PHP服务器,后者托管在apache服务器上。
请给我建议代码的样本
我用这个来发布数据

const newInstance = axios.create({
        url: `http://something.com/import_data/${channelId}`,
        method: 'post',
        headers: {
            "USERKEY": "********",
            "PASSWORD": "*******"
        },
        timeout: 1800000,
        httpAgent: new http.Agent({ keepAlive: true })
    });

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

js81xvg63#

我面临的问题和以前的海报完全一样。
使用axios将多部分/表单数据请求发送到我不控制的API。
从Lambda函数上的node.js脚本,第一个请求工作正常,后续请求则不行。

***但是***来自Postman,情况并非如此,表明这是我的脚本问题,而不是服务器问题。

此外,如果运行脚本的lambda示例是 NEW,而不是简单地重用,则脚本工作正常。
我试过了:

  • 显式设置内容长度标头
  • 使用新的axios https代理代替默认代理
  • 使connection-type = 'close',以便每次都重新创建连接,而不是重复使用连接。

似乎没有什么区别,虽然很明显, Postman 做的事情是正确的,我的脚本不是。
我看不到任何人解决了这个问题--试图转移到另一个http模块(这将是一个耻辱)。

相关问题