最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to resolve NODE.Js HTTP POST "ECONNRESET" Error - Stack Overflow

programmeradmin0浏览0评论

I have this function and the below data which is passed into this function returns a ECONNRESET, socket hang up error. However, when the discountCode array is reduced to like only 10 objects, it can POST without any problem.

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. Any NodeJs ninja could give some insights to this problem?

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 have this function and the below data which is passed into this function returns a ECONNRESET, socket hang up error. However, when the discountCode array is reduced to like only 10 objects, it can POST without any problem.

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. Any NodeJs ninja could give some insights to this problem?

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

}

]}`

Share Improve this question edited Nov 7, 2013 at 5:51 Hong Zhou asked Nov 6, 2013 at 11:11 Hong ZhouHong Zhou 6491 gold badge9 silver badges20 bronze badges 3
  • ECONNRESET means that the server closed the connection for some reason. Maybe it does not accept that amount of data? Is it an own written server API or something where a documentation is available? – Markus Commented Nov 6, 2013 at 11:39
  • Yes it's a own written server api with Java Spring framework. Still looking for the reason why it reject the data. Do you have any idea you could think of? ;) – Hong Zhou Commented Nov 6, 2013 at 12:20
  • 1 can you add an Agent: Mozilla and Connection: Keep-Alive to the headers? – Sanjeev Commented Nov 7, 2013 at 4:04
Add a comment  | 

4 Answers 4

Reset to default 9

I had the same problem and was able to resolve it by adding a Content-Length header:

    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. I assume it's some kind of weirdness in the internal Node.js code. 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. So please leave a comment if you have any idea...

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.

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). Otherwise the POST call will hang with the ECONNRESET error.

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

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

E.g 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,
        }
    );
发布评论

评论列表(0)

  1. 暂无评论