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

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///

Related

http-proxy-middleware econnreset error after successful post request

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

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

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)

Node JS VPN connect to endpoint

I hope you can help!
I have setup and Amazon echo applcation, the application makes a request to and AWS EC2 instance and gets JSON data as a response, this is working as expected however the use case for the final application is to connect to a private IP sending paramaters to an API to return the same JSON DATA.
for many reasons sadly I cannot share any of the endpoint information.
I need my NODE.js Application to make a request to the private IP over a VPN connection, Im currently using OPENVPN to make local requests to the endpoint.
I have looked at node packages to see if this is possible but I cannot seem to find one, except for this package here
https://www.npmjs.com/package/node-openvpn
This package is has a dependancy thats fails to download, so i got the node_module manually but Im getting an error when i try to execute the code
var openvpnmanager = require('node-openvpn');
var opts = {
host: 'xx.xx.xx.xx', // normally '127.0.0.1', will default to if undefined
port: 443, //port openvpn management console
timeout: 1500, //timeout for connection - optional, will default to 1500ms if undefined
logpath: 'log.txt' //optional write openvpn console output to file, can be relative path or absolute
};
var auth = {
user: '*******',
pass: '*******',
};
var openvpn = openvpnmanager.connect(opts)
openvpn.on('connected', function() { //will be emited on successful interfacing with openvpn instance
openvpnmanager.authorize(auth);
});
openvpn.on('console-output', function(output) { //emits console output of openvpn instance as a line
console.log(output)
});
openvpn.on('state-change', function(state) { //emits console output of openvpn state as a array
console.log(output)
});
// openvpnmanager.getLog(console.log) //get all console logs up to this point
// and finally when/if you want to
// openvpnmanager.disconnect();
openvpn.on('disconnected', function() { //emits on disconnect
openvpnmanager.destroy() //finally destroy the disconnected manager
});
this just gives me an error
Unhandled rejection TypeError: Cannot read property 'writable' of undefined
at Telnet.exec (C:\Users\user\Desktop\alexa- po\node_modules\node-openvpn\node_modules\telnet-client\lib\telnet- client.js:90:24)
If anybody has any suggetions on how to make this possible I would be very grateful.

Receiving Twilio 31201 error, despite having well-formed token

I'm using the following code from the Twilio Programmable Video Javascript Quickstart Guide, trying to Initialize the SDK with an access token:
https://www.twilio.com/docs/api/video/guide/identity
// Create an AccessManager to manage our Access Token
var accessManager = new Twilio.AccessManager('$TWILIO_ACCESS_TOKEN');
// Create a Conversations Client and connect to Twilio's backend
conversationsClient = new Twilio.Conversations.Client(accessManager);
conversationsClient.listen().then(function() {
console.log('Connected to Twilio!');
}, function (error) {
console.log('Could not connect to Twilio: ' + error.message);
});
But before even hitting the "could not connect to Twilio" error message designed into the above code, I get the following console error:
twilio-conversations.min.js:91 Client ERROR r {_errorData: Object, name: "LISTEN_FAILED", message: "Gateway responded with: 31201 Unknown authentication error"}
I'm testing this on an https-enabled development server, via ngrok.io. I've followed the code in the tutorial (link above) carefully. Does anyone understand what causes this cryptic 31201 error?

Categories

Resources