簡體   English   中英

從 Node API 到 PHP 服務器的 Axios 調用導致套接字掛斷

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

我使用 Express 在 Nodejs 中創建了一個 API。

在調用 Node API 時,它會讀取一個文件並將其發送到部署在 Apache 中的 PHP 服務器。從 PHP 服務器接收響應並將其發送回我的 Node API 的調用者。 第一次命中我的節點 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');
                });

     })

})

我從第二個 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)我又構建了一個 Node API 只是為了檢查我是否點擊了該 API,然后我會收到套接字掛斷錯誤,但是這個 API每次都運行。即使我在上述 API 上遇到套接字掛斷,這個 API 也能完美運行。

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

仍然無法找到問題的原因。 我找到了一個回旋處,並使用Shell腳本使用Shell.js命中PHP服務器。

此解決方案效果很好。

我面臨同樣的問題......我有相同的過程來發送數據。 節點服務器使用 axios 獲取和發送(發布)數據到托管在 apache 服務器中的 php 服務器。

請給我建議代碼示例

我正在使用它來發布數據

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