简体   繁体   English

如何解决 NODE.Js HTTP POST“ECONNRESET”错误

[英]How to resolve NODE.Js HTTP POST "ECONNRESET" Error

I have this function and the below data which is passed into this function returns a ECONNRESET, socket hang up error.我有这个函数,下面传递给这个函数的数据返回一个 ECONNRESET,套接字挂起错误。 However, when the discountCode array is reduced to like only 10 objects, it can POST without any problem.但是,当 discountCode 数组减少到只有 10 个对象时,它可以毫无问题地 POST。

What could the cause for this problem?这个问题的原因可能是什么? I tried to do multiple req.write() by segmenting the data in Buffer, however that doesn't work out well.我尝试通过对 Buffer 中的数据进行分段来执行多个 req.write(),但是效果不佳。 Any NodeJs ninja could give some insights to this problem?任何 NodeJs 忍者都可以对这个问题提供一些见解吗?

createObj: function(data, address, port, callback) {

//console.log('Create Reward: '+JSON.stringify(data));
var post_data = JSON.stringify(data);

var pathName = '/me/api/v1/yyy/'+data.idBusinessClient+'/newObj';

    // 
    var options = {
        hostname: address,
        port: port,
        path: pathName,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Accept': 'application/json',
            'Accept-Encoding': 'gzip,deflate,sdch',
            'Accept-Language': 'en-US,en;q=0.8'
        }
    };

    // http call to REST API server
    var req = restHttp.request(options, function(res) {

        console.log('HTTP API server PUT Reward response received.');
        var resData = '';
        res.on('data', function(replyData) {

            // Check reply data for error.
            console.log(replyData.toString('utf8'));
            if(replyData !== 'undefined')
                resData += replyData;
        });

        res.on('end', function() {
            //<TODO>Process the data</TODO>             
            callback(JSON.parse(resData));
        });
    });

    req.write(post_data);
    req.end();

    console.log('write end');

    req.on('close', function() {
        console.log('connection closed!');
    });

    req.on('error', function(err) {
        console.log('http request error : '+err);
        callback({'error':err});
        throw err;
    });

    req.on('socket', function(socket) {
        console.log('socket size:'+socket.bufferSize);
        socket.on('data', function(data) {
            console.log('socket data:'+data);
        });
    });

}

]}` ]}`

I had the same problem and was able to resolve it by adding a Content-Length header:我遇到了同样的问题,并且能够通过添加 Content-Length 标头来解决它:

    headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Content-Length': Buffer.byteLength(post_data),
        'Accept': 'application/json',
        'Accept-Encoding': 'gzip,deflate,sdch',
        'Accept-Language': 'en-US,en;q=0.8'
    }

However, I still have no clear idea why a missing Content-Length header causes such a trouble.但是,我仍然不清楚为什么缺少 Content-Length 标头会导致这样的麻烦。 I assume it's some kind of weirdness in the internal Node.js code.我认为这是内部 Node.js 代码中的某种奇怪之处。 Maybe you can even call it a bug, but I'm not sure about that ;)也许您甚至可以称其为错误,但我不确定;)

PS: I'm absolutely interested more information about the cause of this problem. PS:我绝对对有关此问题原因的更多信息感兴趣。 So please leave a comment if you have any idea...因此,如果您有任何想法,请发表评论...

If Express and http-proxy-middleware is used to make the POST call, and some body parser middleware is used like express.json() , the request interceptor fixRequestBody must be used ( more info ).如果使用Expresshttp-proxy-middleware进行 POST 调用,并且使用了一些 body 解析器中间件,例如express.json() ,则必须使用请求拦截器fixRequestBody更多信息)。 Otherwise the POST call will hang with the ECONNRESET error.否则 POST 调用将挂起并出现ECONNRESET错误。

const express = require('express');
const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');

const app = express();
app.use(express.json());
app.post(
  '/path',
  createProxyMiddleware('/path', {
    target: API_URL,
    changeOrigin: true,
    pathRewrite: (path, req) => `/something/${req?.body?.someParameter}`,
    onProxyReq: fixRequestBody // <- Add this line
  });

This might be a cause from the system instead of programming issues. 这可能是系统的原因,而不是编程问题。

http://www.murvinlai.com/remote-http-request.html http://www.murvinlai.com/remote-http-request.html

When you change the content of response for sure you need also to update on header the content length:当您确定更改响应的内容时,您还需要在标题上更新内容长度:

headers: {
    ...
    'Content-Length': Buffer.byteLength(post_data),
    ...
}

But i run on this problem also when i try to make multiple request and seems that this is not well managed on different library so a workaround that i have found if this problem persist is to add on headers:但是当我尝试发出多个请求时,我也遇到了这个问题,并且似乎这在不同的库上没有得到很好的管理,所以如果这个问题仍然存在,我发现一个解决方法是添加标题:

headers: {
    ...
    connection: 'Close'
    ...
}

So if you are making request on different servers.. this close the connection after finish the process.因此,如果您在不同的服务器上发出请求.. 在完成该过程后关闭连接。 This worked for me in net, node-http-proxy.这在网络,node-http-proxy 中对我有用。

Had the same problem.有同样的问题。 The solution for me was to append it to the proxy for it to work.我的解决方案是将其附加到代理以使其工作。 If you're not using a proxy, you can probably just append it to the post request itself.如果您不使用代理,您可能只需将其附加到发布请求本身。

With proxy:使用代理:

import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import logger from './logger';

        // setup routes
        server.get('/isAlive', (req, res) => res.send('Alive'));
        server.get('/isReady', (req, res) => res.send('Ready'));

        server.use(express.static(path.join(__dirname, '../build')));

        const restream = (proxyReq, req, res, options) => {
            if (req.body) {
                let bodyData = JSON.stringify(req.body);
                proxyReq.setHeader('Content-Type', 'application/json');
                proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
                proxyReq.write(bodyData);
            }
        };

        server.use(
            '/api',
            createProxyMiddleware({
                target: 'http://your-backendUrl-api',
                onProxyReq: restream,
                changeOrigin: true,
                proxyTimeout: 30000,
                secure: true,
                logLevel: 'info',
                onError: (err, req, res) => {
                    logger.error('error in proxy', err, req, res);
                },
            })
        );

Eg without proxy:例如没有代理:

import axios, { AxiosResponse } from 'axios';

const api = axios.create({
    baseURL: '/api/....',
    timeout: 35000,
    withCredentials: true,
    headers: { Pragma: 'no-cache', 'Cache-Control': 'no-cache' },
    validateStatus: (status) => status < 400,
});

    const response = await api.post(
        `/somepath/${exampleInjectedId}/somepathToRestAPI`,
        {
         ...payload
        },
        {
            baseURL: '/api/...',
            timeout: 35000,
            withCredentials: true,
            headers: {
                Pragma: 'no-cache',
                'Cache-Control': 'no-cache',
                'Content-Length': Buffer.byteLength(
                    JSON.stringify({
                        ...payload
                    })
                ),
            },
            validateStatus: (status) => status < 400,
        }
    );

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

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