http-proxy-middleware econnreset error after successful post request - javascript

Developing a contact form using Nodejs/Express and create-react-app following this tutorial https://www.youtube.com/watch?v=o3eR0X91Ogs. The issue that I'm running into is that when I hit submit on the form the message succeeds, and I get it in my inbox. However, in the developer console, I am hit with the timeout error I set on the axios.post located in Contact.js, and in my terminal it logs message sent, console log located in index.js, immediately throwing the following error afterward:
HPM ERROR: Error: socket hang up
[1] at connResetException (internal/errors.js:612:14)
[1] at Socket.socketCloseListener (_http_client.js:443:25)
[1] at Socket.emit (events.js:326:22)
[1] at TCP.<anonymous> (net.js:673:12) {
[1] code: 'ECONNRESET'
[1] }
[1] [HPM] Error occurred while trying to proxy request /api/contact/ from localhost:3001 to http://localhost:3000/ (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
Does anyone know why this error is occurring, and how I can fix it? The message sends but hangs afterward which prevents the app state from resetting (resetForm). At the same time, the axios.post in Contact.js doesn't update the state of sent to true.
The Github repo for the project.
Edit: I've been stuck on this for a few days now. Looked at similar questions, attempted ALL the fixes I could find, and this error still persists.

This is a common misunderstanding about how ExpressJs responses work. If you don't send a response to the request, it'll be stuck forever. So all you have to do is to send a response! Also, the res variable was re-defined in the callback of sendMail function. Here is the fix:
app.post('/api/contact', (req, res) => {
// ...
smtpTransport.sendMail(mailOptions, (err, mailResponse) => {
if(err) {
console.log(err);
} else {
console.log('Message sent!');
}
smtpTransport.close();
return res.send(err ? err : 'Message sent!');
});

Related

Accessing Node with React-native returns an unhandled promise rejection warning (id: 0)

I have a test backend route,
router.get("/test", (req, res) => {
console.log("it works!");
return res.json({ msg: "Success from backend" });
});
And in my react-native component, I have a method:
export const registerUser = async () => {
const res = await axios.get("http://localhost:5000/api/users/test");
console.log("response received --> ", res.data);
};
I get the error:
[Unhandled promise rejection: TypeError: Network request failed]
However, when I access http://localhost:5000/api/users/test through my browser, I get the expected response and behaviour.
Not sure what I'm doing wrong here. I've even tried using the react-native-axios library instead of just axios, but I get the same error/warning. Also, I'm translating a functioning ReactJS app to React-native, so I'm positive my backend logic/syntax is configured and correct.
Edit
Full warning below:
Edit 2
Code for axios call:
try {
console.log("trying");
const res = await axios.get("http://localhost:5000/api/users/test", {
headers: {
"Access-Control-Allow-Origin": "*"
}
});
console.log("got it"); // never reached
} catch (err) {
console.log("oh no"); // this doesn't log either, oddly enough
console.log(err);
}
Warning thrown:
[Unhandled promise rejection: TypeError: Network request failed]
* client/node_modules/react-native/Libraries/vendor/core/whatwg-fetch.js:504:29 in onerror
* client/node_modules/event-target-shim/lib/event-target.js:172:43 in dispatchEvent
* client/node_modules/react-native/Libraries/Network/XMLHttpRequest.js:580:29 in setReadyState
* client/node_modules/react-native/Libraries/Network/XMLHttpRequest.js:394:25 in __didCompleteResponse
* client/node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:190:12 in emit
* client/node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:366:47 in __callFunction
* client/node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:106:26 in <unknown>
* client/node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:314:10 in __guard
* client/node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
Using Postman or directly from browser works.. through React-native it doesn't
The local development server cannot be accessed because the port has not yet been passed on by the ADB. Therefore, in this situation, you can map a local server port or use a local IP address to perform two tasks.
Obtain the port from the ADB by executing the following command at the terminal:
adb reverse tcp:5000 tcp:5000
OR
You can also use local IP. Shake the instrument or press and hold the menu button to open the developer menu. Click Open Dev Settings, and then click Next. then tap Debug server host & port for device. Here you can enter your machine's local IP with port number 5000
Example
192.168.1.50:5000

JSON/EJSON Error w/ Stripe API - Invoice Webhook Event

Update w/ Additional Info - 18 Dec.
As I test further it appears that the error is isolated to the "this.response.end(json);" See notes below:
stripe non-invoice event:
a) "this.response.end(EJSON.stringify(obj, {indent: true}));" works & returns 200
b) "this.response.end(EJSON.stringify(obj));" no error on local server, error on stripe dashboard with 'unable to connect' and does not return code 200
stripe invoice event:
a) "this.response.end(EJSON.stringify(obj, {indent: true}));" throws errors - see details below.
b) "this.response.end(EJSON.stringify(obj));" no error on local server, error on stripe dashboard with 'unable to connect' and does not return code 200
Any insight would be appreciated.
I am having some issues with the Stripe API and am seeking some help or insight. I am using ngrok to test the Stripe webhooks locally and everything works fine until I make a request to any Stripe 'invoice' event type (e.g. invoice.payment_succeeded). When I run a test on any 'invoice' event type I get several errors:
my running application breaks (i.e. requires me to type meteor run in the terminal to restart the app)
I receive this server side error message in my terminal:
///error message start///
events.js:183
throw er; // Unhandled 'error' event
^
Error: write after end
at write_ (_http_outgoing.js:622:15)
at ServerResponse.write (_http_outgoing.js:617:10)
at IncomingMessage.ondata (_stream_readable.js:639:20)
at emitOne (events.js:116:13)
at IncomingMessage.emit (events.js:211:7)
at IncomingMessage.Readable.read (_stream_readable.js:475:10)
at flow (_stream_readable.js:846:34)
at resume_ (_stream_readable.js:828:3)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
///error message end///
On my Stripe dashboard I get an error: 'Test webhook error: Unable to connect'
Again this only breaks when I make a request to any Stripe 'invoice' event type (e.g. invoice.payment_succeeded).
I contacted Stripe to see if there was anything else I should consider but they said things were fine on their end.
One final point, to get ngrok running I use 'ngrok http 3000'.
With that said my server side webhook code is below. If anyone has any insight on what would be causing this error, any insight perspective would be appreciated.
///server side webhook code start///
Router.route('/webhooks/stripe', { where: 'server' })
.get(function () {
console.log('getter');
this.response.end('closing...');
})
.post(function () {
console.log('post function initiated');
// stores payload as string
var obj = this.request.body;
console.log("print obj var");
console.log(obj);
// saves as indented string to send as response
var json = EJSON.stringify(obj, {indent: true});
this.response.writeHead(200, {
'Content-Length': json.length,
'Content-Type': 'application/json'
});
this.response.end(json);
})
.put(function () {
console.log('put');
});
///server side webhook code end///
I was able to solve this issue. For reference and posterity I removed the commented code below and manually added my status code (i.e. this.response.statusCode = 200;). This got things working and resolved the issue.
///code snippet start///
var json = EJSON.stringify(obj, {indent: true});
//this is the code i removed
// this.response.writeHead(200, {
// 'Content-Length': json.length,
// 'Content-Type': 'application/json'
// });
//this is the code i added to send a manual status code
this.response.statusCode = 200;
this.response.end(json);
///code snippet end///

Sending 500 ("Server Error") response when visiting any url in Sails App

I am using Sails and Mysql to handle the database of my app. I recently clicked on a chrome autofill URL that took me to a 404'd page, since that url localhost:1337/companies was not active in this project.
Ever since I did that, my app returns
error: Sending 500 ("Server Error") response:
Error (E_UNKNOWN) :: Encountered an unexpected error
: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'where clause'
and
Details: Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'where clause'
any time I go to a url in my app. I tried cloning my app and relinking the database to no avail. I see this is a common issue people run into with sails, but none of the mentioned solutions were able to fix it for me.
Everything was working before I clicked that URL which makes me believe it may be a route issue, but the app still works, it will just fill up my terminal with the above errors.
Any help is greatly appreciated!
Edit: this is the custom API call I was working on in my controller.js when I started seeing the error:
winner: function (req, res) {
User.findOne({id: req.param('id')}).exec(function(err, user) {
if (err) {
return res.negotiate(err);
}
else {
var u = user;
u.totalwins++;
u.save();
sails.io.sockets.emit("chat", {verb:"score", data:{id: req.param('id'), name: user.name}});
}
});
}
Also receiving this error in my chrome-browser console:
:1337/user/quizzes Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Failed to load resource: net::ERR_CONNECTION_REFUSED on NodeJs ,AngularJs Web Application

when i run my web application i get this error.this was happened suddenly.my application is MEAN stack appllication whicj has a end to end connection through APIs.
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.res.set.res.header (D:
this is an API that is being exposed.
app.post('/api/filesReadUpload', function(req, res) {
var eventReadUpload=new filesReadUpload({
//id:req.body.id,
dat:req.body.dat,
details:req.body.details,
tim:req.body.tim,
// space:req.body.space
});
eventReadUpload.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Read file!' });
});
});
can anyone support with this.if this information is not enough please inform me.
Thanks
The ERR_CONNECTION_REFUSED appears because the server is down. The reason why the server is down is because of the error you pointed:
Error: Can't set headers after they are sent.
That means you tried to send the response twice. In case of error you have to run return res.send(err) because you want to not call the res.json in case of error. If you do (what currently is happening), you will get that error.
eventReadUpload.save(function(err) {
if (err)
return res.send(err);
res.json({
message: 'Read file!'
});
});
You will have to figure out why the saving fails, but this will fix the initial problem.

net::ERR_CONNECTION_REFUSED Error jQuery ajax node.js

This error happens when the date change in the date input happens very quickly. If I change the date every 2+ seconds, it works fine. But it gives the following error when the date input is changed very fast. In short, this error happens only when the next request is made right after the first one very quickly. I've spent hours and search a lot of similar issue with this error ERR_CONNECTION_REFUSED on SO and google, but no luck. Any ideas of what's causing this issue?
Also, when load the url (http://localhost:8000/svc/diary/2016-01-03) in browser, the data comes out fine, but if I reload (Ctrl + R) the url very fast, it goes to yahoo search with these terms:
http localhost 8000 svc diary 2016 01 03 diary
The Error Message from the console:
GET http://localhost:8000/svc/diary/2016-01-03 net::ERR_CONNECTION_REFUSED
send # jquery-2.2.0.js:9172
jQuery.extend.ajax # jquery-2.2.0.js:8653
(anonymous function) # idiary.js:18
jQuery.event.dispatch # jquery-2.2.0.js:4732
elemData.handle # jquery-2.2.0.js:4544
The Date form
<input class="form-control" id='ddate' type="date" name="bday">
The Ajax Call
$('#ddate').on('change', function() {
var ajaxParams = {
url: '/svc/diary/' + $(this).val(),
type: 'GET',
contentType: "application/json",
dataType:"json"
};
console.log(ajaxParams);
$.ajax(ajaxParams)
.done(function (data, textStatus, jqXHR) {
console.log("diary retrieved!")
console.log(data);
$("#diary").text(data.diary);
})
.fail(function (jqXHR, textStatus, errorThrown) {
$("#diary").text("");
console.log("failed to retrieve diary!");
console.log(errorThrown);
});
});
The backend node.js GET handler
function getDiary(req, res) {
var date = req.params.date;
util.log(mysql.format(searchQuery, [date]));
util.dbpool.query(searchQuery, [date], function (err, result) {
res.setHeader("Content-Type", "application/json");
if (err) {
console.log(err);
util.errLog(JSON.stringify(err));
res.status(500).json({message: 'summary, no results.'});
} else {
console.log(result);
result.length > 0 ? res.status(200).json(result[0]) : res.status(200).json({"ddate":date, "diary":""});
}
});
}
UPDATE: Just found out, this issue is gone when starting the node application server with
node server.js
This issue happens only when starting the node application server with pm2 or foerver
pm2 start --watch server.js
forever start --watch server.js
The issue is resolved. It was caused by using the watch flag in pm2 and forever. My app prints log statements, and the log folder is in the same level as the application folder, so whenever a log file is updated, pm2 is restarting my application server. That is why it works if I pin my application server every few seconds because the server restart only takes about a second. It gives connection refused error if I pin the server very fast, because the server is still restarting, that's why it's connection refused.
You are looking to make a cross domain request. By default server disallows this. You need to enable it on your server, and make a JSONP request. You can read about it here:
http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html
What is JSONP all about?

Categories

Resources