Express or Axios Error: socket hang up code: ECONNRESET - node.js

This is the first time i post a question here, sorry if some data is missing.
I'm trying to do some web scraping to get some info of a table.
The page only responds with an index.php and when i use the search form, it makes a POST to index.php?go=le with some formData.
To avoid the CORS problem, im making the post with my own API running in localhost. I'm pointing my frontend to my API and i get the response from localhost.
No problem there.
My problem appears when i try to make a second request to my API. The first GET works fine but after that response it keeps failing.
When i restart the server, it works again but only one time.
Here is my API code. I use nodemon server.js to start my server.
server.js
const express = require("express");
const axios = require("axios");
const scrape = require("scrape-it");
const FormData = require("form-data")
const cors = require("cors")
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors())
const config = {
headers: {
'Content-type': 'multipart/form-data'
},
}
app.get("/get-projects", async (req,res) => {
const testJSON = await axios.post(baseURL +"/index.php?go=le",formData,config)
.then(res => {
console.log("Post successfull...");
return res
}
)
.catch(err => {
console.log("Server error");
return err
}
);
if(testJSON && testJSON.data){
res.send({status: 200, data: testJSON.data});
}else{
res.status(508).send({status: 508, msg: "Unhandled Server Error", failedResponse: testJSON || "empty"})
}
})
app.listen(PORT,()=>console.log(`App running in port: ${PORT}`))
And in my front-end i only have a button with an event that makes a get to my API (http://localhost:5000)
This is my fetch.js that is included by a script tag. Nothing fancy there.
fetch.js
const btn = document.getElementById("btn-fetch-proyects")
const axios = window.axios
const fetchProjects = async () => {
console.log("Fetching...")
axios.get("http://localhost:5000/get-projects")
.then(res=>
console.log("The server responded with the following data: ",res.data)
)
.catch(err => console.log("Failed with error: ",err)
)
return null
}
btn.addEventListener("click",fetchProjects);
In the console where im running the server, i get Server error with this err object:
{
"message": "socket hang up",
"name": "Error",
"stack": "Error: socket hang up\n at connResetException (internal/errors.js:607:14)\n at Socket.socketOnEnd (_http_client.js:493:23)\n at Socket.emit (events.js:327:22)\n at endReadableNT (internal/streams/readable.js:1327:12)\n at processTicksAndRejections (internal/process/task_queues.js:80:21)",
"config": {
"url": "http://186.153.176.242:8095/index.php?go=le",
"method": "post",
"data": {
"_overheadLength": 1216,
"_valueLength": 3,
"_valuesToMeasure": [],
"writable": false,
"readable": true,
"dataSize": 0,
"maxDataSize": 2097152,
"pauseStreams": true,
"_released": true,
"_streams": [],
"_currentStream": null,
"_insideLoop": false,
"_pendingNext": false,
"_boundary": "--------------------------935763531826714388665103",
"_events": {
"error": [
null,
null
]
},
"_eventsCount": 1
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "multipart/form-data",
"User-Agent": "axios/0.21.1"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
},
"code": "ECONNRESET"
}
I hope someone has a clue about what's happening. I tried all day and i couldn't solve it.
I tried posting to other sites, and it works fine. I thing the problem is with the form POST.
Thanks for reading!!!

At a first glance I see an error in your front-end code. You are using async on the function but then you do not await but you use .then, try not mixing up styles, either you use async/await or .then .catch.
Check if that helps! :)

Obviously the socket is hanging!
Use node unirest and it closes the data stream.
var unirest = require('unirest');
var req = unirest('POST', 'localhost:3200/store/artifact/metamodel')
.attach('file', '/home/arsene/DB.ecore')
.field('description', 'We are trying to save the metamodel')
.field('project', '6256d72a81c4b80ccfc1768b')
.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.raw_body);
});
Hope this helps!

Related

Axios request working fine by itself but when I try to integrate it with my discord bot it always returns an error?

const { SlashCommandBuilder } = require("#discordjs/builders");
const axios = require("axios")
const { XRapidAPIKey, XRapidAPIHost} = require("../config.json");
module.exports = {
data: new SlashCommandBuilder()
.setName('stock')
.setDescription('Replies with the name of the stock and its current price.')
.addStringOption(option =>
option.setName('ticker')
.setDescription('The stock you want the price of.')
.setRequired(true)),
async execute(interaction) {
const ticker = interaction.options.getString('ticker');
const options = {
method: 'GET',
url: `https://realstonks.p.rapidapi.com/${ticker.toUpperCase()}`,
headers: {
"X-RapidAPI-Key": XRapidAPIKey,
"X-RapidAPI-Host": XRapidAPIHost
}
};
axios.request(options).then(function(response) {
interaction.reply(response.data);
}).catch(function(error) {
console.log(error);
});
}
this is the code for the stock price command but it does not work due to an error being thrown. It should send a message in my discord server with the json data from the axios request. It at first didn't work because I tried to put it in a function and return it but I realized that it needs to be in the command function but I cannot figure out why the request is returning a http 400 code even though it works fine by itself.
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async CommandInteraction.reply (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:103:5) {
method: 'post',
path: '/interactions/986055380461301820/aW50ZXJhY3Rpb246OTg2MDU1MzgwNDYxMzAxODIwOnY5c1QzbDdIWVN0NW4zY2d4ODd6M2RRSHA1OVpORHZ5SmFXUkNyY0pKZDNpNGNyVjFtQzZ5UjFYck96ZHhJUVlVNjJ6YWNHRTBFbFBSczlWWXBTdHk2YzFuNFJrRFU5R3R3dDAyQ3ByRmtiaTBpRm1NYUVyRXVHYjhsUk84T25t/callback',
code: 50006,
httpStatus: 400,
requestData: {
json: {
type: 4,
data: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
}
},
files: []
}
}
But when I run the code in its own file without the discord related stuff and console.log the data it outputs the json data as you would expect.

Next JS - How to fix Error: connect ECONNREFUSED 127.0.0.1:3003 at TCPConnectWrap.afterConnect [as oncomplete]

I am new to Next JS.
I can't build my application locally. When I enter the npm run build command I get the following errors :
...
_currentUrl: 'http://localhost:3003/data/menus.json',
[Symbol(kCapture)]: false
},
response: undefined,
isAxiosError: true,
toJSON: [Function: toJSON]
}
Error: connect ECONNREFUSED 127.0.0.1:3003
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1148:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3003,
config: {
url: 'http://localhost:3003/data/menus.json',
method: 'get',
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.21.4'
},
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
adapter: [Function: httpAdapter],
...
Et à la fin du log
...
info - Generating static pages (771/771)
> Build error occurred
Error: Export encountered errors on following paths:
/ar
/ar/classic
/ar/minimal
/ar/standard
/ar/vintage
/de
/de/classic
/de/minimal
/de/standard
/de/vintage
/en
/en/classic
/en/minimal
/en/standard
/en/vintage
/es
/es/classic
/es/minimal
/es/standard
/es/vintage
/fr
/fr/classic
/fr/minimal
/fr/standard
/fr/vintage
/he
/he/classic
/he/minimal
/he/standard
/he/vintage
/zh
/zh/classic
/zh/minimal
/zh/standard
/zh/vintage
at C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\export\index.js:487:19
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async Span.traceAsyncFn (C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\telemetry\trace\trace.js:60:20)
at async C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\build\index.js:833:17
at async Span.traceAsyncFn (C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\telemetry\trace\trace.js:60:20)
at async C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\build\index.js:707:13
at async Span.traceAsyncFn (C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\telemetry\trace\trace.js:60:20)
at async Object.build [as default] (C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\build\index.js:77:25)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed.
Exit code: 1
Command: C:\Program Files\nodejs\node.exe
Arguments: C:\Users\PC\.node\corepack\yarn\1.22.15\lib\cli.js build
Directory: C:\Users\PC\OneDrive\Documents\lab\samara\laravel\shop
Output:
info Visit https://yarnpkg.com/en/docs/cli/workspace for documentation about this command.
error Command failed with exit code 1.
The npm run dev command works without any problem. So locally the application has no problem. But when I go to production, I want to build I get these errors above.
Here is my server.js file:
// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
const port = 3003;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer(async (req, res) => {
try {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === '/a') {
await app.render(req, res, '/a', query);
} else if (pathname === '/b') {
await app.render(req, res, '/b', query);
} else {
await handle(req, res, parsedUrl);
}
} catch (err) {
console.error('Error occurred handling', req.url, err);
res.statusCode = 500;
res.end('internal server error');
}
}).listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://${hostname}:${port}`);
});
});
And my package.json file
{
"name": "#samara/shop",
"version": "1.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3003",
"build": "next build",
"start": "NODE_ENV=production node server.js"
If you need another file to check let me know.
I don't know if it's the best way but in my case I run npm run dev then run npm run build and the error stops happening
then stop the dev and run npm run start
you can also add a try catch in the api call http://localhost:3003/data/menus.json
if you are calling in a getStaticProps function, you can in the catch set the revalidity to 1 second if you need to revalidate
This one is a duplicate of a:
ECONNREFUSED during 'next build'. Works fine with 'next dev'
The issue is explained quite well in this thread.
Essentially as the comment states:
You should not fetch an API route from getStaticProps...
Please check also Ciro Santilli answer, he gives more details to the issue

Axios - Getting socket hang up error while running it on docker container

I am trying to get results from third party API by using Axios npm. Using nested request, first request is to get the token and another one is to get results.
Below code is working fine in my local machine but not in Docker container.
var config = {
method: 'post',
url: gsecConfig.tokenUrl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function (response) {
if (response.data.access_token) {
const config = {
headers: { Accept: 'application/json', Authorization: `Bearer ${response.data.access_token}` }
};
axios.get(gsecConfig.gsecUrl + gsecid, config)
.then(function (response) {
let supplierData = response.data;
res.status(200).json({
"data": supplierData
});
}).catch(function (error) {
res.json({
"errors": error.message,
"name": error.name
});
});
}
})
.catch(function (tokenError) {
if (tokenError) {
res.json({
"errors": tokenError.message,
"name": tokenError.name
});
}
});
});
Getting error like below
"message": "socket hang up",
"name": "Error",
"stack": "Error: socket hang up\n at createHangUpError (_http_client.js:323:15)\n at Socket.socketOnEnd (_http_client.js:426:23)\n at Socket.emit (events.js:203:15)\n at endReadableNT (_stream_readable.js:1129:12)\n at process._tickCallback (internal/process/next_tick.js:63:19)",
"code": "ECONNRESET"
Thanks in advance!
If your server is not Kubernetes, you can change the publish mode to host (default is ingress), the problem will be solved. check this
You can change it in docker-stack like below:
ports:
- target: 3001
published: 3001
protocol: tcp
mode: host
But if this is Kubernetes with node clusters, you should use the ingress mode, I'm facing this issue and still stuck here. Hope someone can help.

read ECONNRESET error occurs in nextjs geinitialProps when sending get request to api

This error occured in next.js app when i send a get request using axios in getInitialPros of _app.js file.
if (typeof window === "undefined") {
// user = await checkAuth(ctx);
// const token = ctx.req.headers.cookie;
console.log("TOKEN", ctx.req.headers);
if (ctx.req && ctx.req.headers.cookie) {
try {
res = await axiosClient("get", { cookie: ctx.req.headers.cookie }).get(
"/auth/currentuser"
);
user = res.data;
console.log("USER IN SERVER SIDE", user);
ctx.store.dispatch(setAuthenticatedUser(res.data));
} catch (err) {
console.log("ERROR in APP", err);
// console.log("USER FOUND IN APP.JS", res.data);
ctx.store.dispatch(removeAuthenticatedUser());
}
}
} else {
try {
res = await axiosClient("get").get("/auth/currentuser");
user = res.data;
// await checkAuth(ctx);
// await checkAuth(ctx,)
console.log("IN CLIENT", res.data);
} catch (err) {}
}
this error occurred when the page is refreshed but it only occurs on server side, not in client side.
ERROR in APP Error: read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:205:27) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read',
config: {
url: '/auth/currentuser',
method: 'get',
headers: {
Accept: 'application/json, text/plain, */*',
cookie: 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZjNhYTJlMmQxN2YxMzAxYTA0NGUxYTIiLCJpYXQiOjE1OTgyODUyMDMsImV4cCI6MTU5ODI4ODgwM30.qtaW-D9P6tJHzL1uHZs3wlzF39UPVkPTLEieuqaVEJY',
'User-Agent': 'axios/0.19.2'
},
baseURL: 'https://tatkaladda.com/api/',
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
this error only occurred in production app not in development mode.
Node.js is not aware of any baseURL. Your browser is. So on the server side you have to provide the full path, on the client side when using relative links they're relative to the base url, eg https://example.com
By: Tim Neutkens - Co-author of Next.js and MDX
One of the suggested workaround is to use full path in the getInitialProps when using axios. In your case change this:
res = await axiosClient("get").get("/auth/currentuser");
to
res = await axiosClient("get").get("http://localhost:3000/auth/currentuser");
//or use external domian if you not on localhost i.e. https:api.example.com/auth/currentuser
If still this does not work, use axios API and set full path on baseUrl as follow:
// axios call
await axios({
method: 'GET',
url: 'http://abc.herokuapp.com/api/' //or baseURL: 'http://abc.herokuapp.com/api/'
)}
Have time! kindly read this, it might help: https://github.com/vercel/next.js/issues/5009
UPDATE
Also you can try to construct your baseURL from getInitialProps context
async getInitialProps({ req }) {
const protocol = req.headers['x-forwarded-proto'] || 'http'
const baseUrl = req ? `${protocol}://${req.headers.host}` : ''
const res = await fetch(baseUrl + '/api/recent/1')
...
}

Elastic search gives Bad request for ping

Code in elasticsearch.js file
function es() {
throw new Error('Looks like you are expecting the previous "elasticsearch" module. ' +
'It is now the "es" module. To create a client with this module use ' +
'`new es.Client(params)`.');
}
es.Client = require('./lib/client');
es.ConnectionPool = require('./lib/connection_pool');
es.Transport = require('./lib/transport');
es.errors = require('./lib/errors');
module.exports = es;
var elasticsearch = require('elasticsearch')
var client = new es.Client({
host: 'localhost:9200',
log: 'trace',
})
// Ping the cluster
client.ping({
requestTimeOut: 30000,
},
function(error){
if(error) {
console.log(error)
console.error("elasticsearch cluster is down!")
}
else {
console.log("All is well")
}
})
and I am running elastic search locally with command $bin/elasticsearch
but when I do $node elasticsearch.js it gives the error saying
Elasticsearch INFO: 2018-01-22T11:17:50Z
Adding connection to http://localhost:9200/
Elasticsearch DEBUG: 2018-01-22T11:17:50Z
starting request {
"method": "HEAD",
"requestTimeout": 3000,
"castExists": true,
"path": "/",
"query": {
"requestTimeOut": 30000
}
}
Elasticsearch TRACE: 2018-01-22T11:17:50Z
-> HEAD http://localhost:9200/?requestTimeOut=30000
<- 400
Elasticsearch DEBUG: 2018-01-22T11:17:50Z
Request complete
{ Error: Bad Request
at respond (/Users/ElasticSearchServer/node_modules/elasticsearch/src/lib/transport.js:307:15)
at checkRespForFailure (/Users/ElasticSearchServer/node_modules/elasticsearch/src/lib/transport.js:266:7)
at HttpConnector.<anonymous> (/Users/ElasticSearchServer/node_modules/elasticsearch/src/lib/connectors/http.js:159:7)
at IncomingMessage.bound (/Users/ElasticSearchServer/node_modules/elasticsearch/node_modules/lodash/dist/lodash.js:729:21)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
status: 400,
displayName: 'BadRequest',
message: 'Bad Request',
path: '/',
query: { requestTimeOut: 30000 },
body: undefined,
statusCode: 400,
response: '',
toString: [Function],
toJSON: [Function] }
elasticsearch cluster is down!
If I try adding new index, delete index, check the health or search, it works fine and gives the appropriate result.
Can anyone help me to fix the issue? thanks in advance!
In the new JavaScript client every option that is not intended for Elasticsearch lives in a second object, your code should be updated as follows:
'use strict'
const { Client } = require('#elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })
client.ping({}, { requestTimeout: 20000 }, (err, response) => {
...
})
In the response object other than body, statusCode, and headers, you will also find a warnings array and a meta object, which should help you debug issues.
In this case, warnings contained the following message: 'Client - Unknown parameter: "requestTimeout", sending it as query parameter'.

Resources