What is the best way to display Flash messages in Express.js? - javascript

I have nodejs app in Ejs framework , I'am a newbie to java script,
I need to know what is the correct way to set flash messages in Node.js
My Code given below throws me an error ,like this :
C:\Users\sad\Desktop\Node Application\routes\users.js:57
req.flash('error_mesg', 'A User with this name already exisit !!')
^
TypeError: Cannot read property 'flash' of null
at Request._callback (C:\Users\as\Desktop\Node Application\routes\users.js:57:10)
at Request.self.callback (C:\Users\sa\Desktop\Node Application\node_modules\request\request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (C:\Users\sd\Desktop\Node Application\node_modules\request\request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (C:\Users\sd\Desktop\Node Application\node_modules\request\request.js:1091:12)
at IncomingMessage.g (events.js:291:16)
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:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Here goes my code where I initiate everything :
var flash = require('connect-flash');
// Global VArs
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
And here goes my Code where I really apply it :
var errors = req.validationErrors();
if(errors){
res.render('register' ,{
errors:errors
})
}else{
var newUser = {first_name,last_name, role,email,password,company,role}
request({
url: "http://127.0.0.1:8000/v1/dashboard/register/",
method: "POST",
json: true, // <--Very important!!!
body: newUser
}, function (req, res, err, body){
var status = res['statusCode']
console.log(typeof(status));
if (status = '400'){
req.flash('error_mesg', 'A User with this name already exisit !!')
}
});
}
There some related answers to this type of question but not specifically flash messages .
Here goes my html :{{#if error_msg}}
<div class="alert alert-danger">{{error_msg}}</div>
{{/if}}

Assuming the last bit of code you posted is the body of an express endpoint, I'm guessing you overwrote your express callback variables req and res in your callback to request. Also, that is not the current function signature for the request library callback, it should be function (error, response, body), not function (req, res, err, body). Fix the function signature, use unique variable names and it should work:
var errors = req.validationErrors();
if(errors){
res.render('register' ,{
errors:errors
})
}else{
var newUser = {first_name,last_name, role,email,password,company,role}
request({
url: "http://127.0.0.1:8000/v1/dashboard/register/",
method: "POST",
json: true, // <--Very important!!!
body: newUser
}, function (error, response, body){
var status = response.statusCode;
console.log(typeof(status));
if (status = '400'){
req.flash('error_mesg', 'A User with this name already exisit !!')
});
}

Related

How to show result body from node JS request to browser?

I new to nodeJS and i want to show my request result body to browser using express, but my code throw an error like this, i've try to use array.push() but not working too
ERROR
node:_http_outgoing:576
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (C:\xampp\htdocs\#masgalih\tt\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\xampp\htdocs\#masgalih\tt\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\xampp\htdocs\#masgalih\tt\node_modules\express\lib\response.js:267:15)
at ServerResponse.send (C:\xampp\htdocs\#masgalih\tt\node_modules\express\lib\response.js:158:21)
at Request._callback (C:\xampp\htdocs\#masgalih\tt\index.js:12:24)
at Request.self.callback (C:\xampp\htdocs\#masgalih\tt\node_modules\request\request.js:185:22)
at Request.emit (node:events:390:28)
at Request.<anonymous> (C:\xampp\htdocs\#masgalih\tt\node_modules\request\request.js:1154:10) {
code: 'ERR_HTTP_HEADERS_SENT'
}
CODE
const request = require('request')
const express = require('express')
const app = express()
app.get('/getdata', (req, res) => {
if (req.query.id !== undefined && req.query.id !== '') {
request('http://localhost/myApi/index.php?id=' + req.query.id, (err, response, body) => {
return res.send({
status: 200,
data: body
})
})
}
return res.send({
status: 400,
msg: 'Parameter invalid'
})
})
app.listen(2000)
The app.get('/getdata'); has two different res.send();'s in it. This by itself is alright, but what is happening is that when the function in app.get('/getdata'); runs, it checks that if statement first. If the if is false, it skips right past and everything runs fine.
But what if the if statement is true? Well, the code inside the the statement runs and sends a request to the specified URL and waits for a response. While it's waiting though, JavaScript continues running your code because JavaScript is asynchronous.
So the second res.send() runs, but then the response to the request is received, and therefore sends a second (the first in chronological order) res.send(), which is why the error is saying you are trying to set headers (the main information in a nodejs request) after you just sent it to the client.
What the code should do is instead only run on or the other, not both. We can achieve this by putting the second res.send() in an else, which means it only runs if the if statement is false. So something like this:
const request = require('request')
const express = require('express')
const app = express()
app.get('/getdata', (req, res) => {
if (req.query.id !== undefined && req.query.id !== '') {
request('http://localhost/myApi/index.php?id=' + req.query.id, (err, response, body) => {
return res.send({
status: 200,
data: body
})
})
} else {
return res.send({
status: 400,
msg: 'Parameter invalid'
})
}
})
app.listen(2000)

replit error? SyntaxError: Unexpected token < in JSON at position 0 ,if not,how to slove it?

Im trying to make a discord account generator and using ouo.io to upload the accounts in,but everytime i try to gen,replit died.
<!DOCTYPE HTML>
^
SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (/home/runner/AccountGenerator/node_modules/hastebin-save/src/upload.js:18:52)
at IncomingMessage.emit (events.js:326:22)
at IncomingMessage.EventEmitter.emit (domain.js:483:12)
at endReadableNT (_stream_readable.js:1241:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
repl process died unexpectedly: exit status 1
upload.js code:
const https = require('https');
const config = require('./../config.json')
module.exports = function(text, callbackFunction){
var req = https.request({
headers: {
"Content-Type": "application/json; charset=utf-8"
},
host: config.host,
port: config.port,
path: config.path,
method: "POST"
}, clb => {
var data = "";
clb.on('data', buffer => {
data += buffer;
});
clb.on("end", () => {callbackFunction(JSON.parse(data).key)});
});
req.write(text);
req.end();
}

Issue with posting data to external API using Node and Express

I am trying to post data from my form to MailChimp API server with node.js and express. However, I am getting an error message that seems strange to debug. I have checked my index.html file and all is well there. Please help me figure out a solution or point me in the right direction. Kindly check out my code below:
const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public"));
app.listen(3000, function(){
"Server is running on Port 3000!"
});
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(req, res){
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
console.log(firstName, lastName, email);
var data= {
members: [
{
email_address : email,
status : "subscribed",
merge_fields : {
FNAME : firstName,
LNAME : lastName
}
}
]
};
var jsonData = JSON.stringify(data);
const url ="https://us10.api.mailchimp.com/3.0/lists/{apikey}";
const options = {
method: "post",
auth: "xxxx:xxxx"
}
const request= https.get(url, options, function(response){
response.on("data", function(data){
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
});
This is the error I am getting.
events.js:200
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at write_ (_http_outgoing.js:594:17)
at ClientRequest.write (_http_outgoing.js:586:15)
at C:\Users\Iredafe\Desktop\Web Development practice\Email-List\app.js:48:9
at Layer.handle [as handle_request] (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\index.js:275:10)
Emitted 'error' event on ClientRequest instance at:
at writeAfterEndNT (_http_outgoing.js:649:7)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
[nodemon] app crashed - waiting for file changes before starting...
You can use axios for simplicity.
const axios = require('axios');
const headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(url,postPayload,headers)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
I just found the answer. It was a bug in my code. I am using the native https method in Node hence I ought not to use https.get here:
const request= https.get(url, options, function(response){
response.on("data", function(data){
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
the correct code that solved the problem was using the http.request instead of http.get:
const request= https.request(url, options, function(response){
response.on("data", function(data){
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
Hope it helps someone in the future!

Cannot parse response SOAP Node.js

firstly sorry for my english, secondly I have a question about use of SOAP in Node.js. I am a beginner with node.js and I need help. This is my function:
var soap = require('soap');
var url = 'http://SOMETHING?wsdl';
var args = {
accountId: 'xxxxx',
userName: 'xxxxx',
password: 'xxxxxx',
targetNSAlias: 'tns',
targetNamespace: 'http://api.ilient.com/'
};
soap.createClient(url, function(err, client) {
if(err) throw err;
client.login(args,function(err, result, raw, soapHeader){
if(err) throw err;
console.log(result);
});
});
when I run I get this error:
Error: Cannot parse response
at /root/node_modules/soap/lib/client.js:321:21
at Request._callback (/root/node_modules/soap/lib/http.js:117:5)
at Request.self.callback (/root/node_modules/request/request.js:186:22)
at Request.emit (events.js:98:17)
at Request.<anonymous> (/root/node_modules/request/request.js:1081:10)
at Request.emit (events.js:95:17)
at IncomingMessage.<anonymous> (/root/node_modules/request/request.js:1001:12)
at IncomingMessage.g (events.js:180:16)
at IncomingMessage.emit (events.js:117:20)
at _stream_readable.js:944:16
someone can help me solve it?
Thanks and sorry for my english again.
I faced a similar problem. Maybe the SOAP web service that you are trying to consume has v1.2 specification and it might expect the content type as application/soap+xml instead of text/xml. In order to force node-soap to use SOAP 1.2 version you could add forceSoap12Headers: true among createClient() parameters.
On a side note, I had to add the ws-addressing headers to soap header because of The message with To ' ' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher error.
I edited your code as follows:
var soap = require('soap');
var url = 'http://SOMETHING?wsdl';
var args = {
accountId: 'xxxxx',
userName: 'xxxxx',
password: 'xxxxxx',
targetNSAlias: 'tns',
targetNamespace: 'http://api.ilient.com/'
};
var soapOptions = {
forceSoap12Headers: true
};
var soapHeaders = {
'wsa:Action': 'http://tempuri.org/MyPortName/MyAction',
'wsa:To': 'http://SOMETHING.svc'
};
soap.createClient(url, soapOptions, function(err, client) {
if(err) throw err;
client.addSoapHeader(soapHeaders, '', 'wsa', 'http://www.w3.org/2005/08/addressing');
client.login(args, function(err, result, raw){
if(err) throw err;
console.log(result);
});
});
Add this code: client.setSecurity(new soap.BasicAuthSecurity('username', 'password')); after your create client code. It worked for me:
var soap = require('soap');
var url = 'http://SOMETHING?wsdl';
soap.createClient(url, function(err, client) {
if(err) throw err;
client.setSecurity(new soap.BasicAuthSecurity('username', 'password'));
client.login(args, function(err, result) {
if(err) throw err;
console.log(result);
});
});

Can't get plotly + node.js to stream data coming through POST requests

I'm trying to get plotly to stream data received by my server through a POST request to http://localhost:3000/step.
Building on the rest-example.js in plotly-nodejs/examples, here's my server code (I've blurred out my username, apikey, and token):
'use strict';
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var events = require('events');
var eventEmitter = new events.EventEmitter();
var app = express();
var server = require('http').Server(app);
var port = process.env.PORT || 3000;
server.listen(port);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/step', function(req, res) {
var data = req.body.data;
eventEmitter.emit('step', data);
res.end('ok');
});
var plotly = require('plotly')('username', 'apikey');
var token = 'token';
var dataInit = [{x:[], y:[], stream: { token: token, maxpoints: 10 } }];
var layout = {fileopt : "extend", filename : "REST-test"};
plotly.plot(dataInit, layout, function (err, msg) {
if(err) return console.error('step data error', err.stack);
var stream = plotly.stream(token, function() {});
eventEmitter.on('step', function(data) {
console.log('sending to plotly: ' + data + ' steps');
var streamObject = JSON.stringify({ x: getDateString(), y: data });
stream.write(streamObject+'\n');
});
});
function getDateString() {
var d = new Date();
return d.toLocaleString();
};
When I POST data using cURL, for example curl http://localhost:3000/step --data "data=5", I can see that the data reaches the callback inside the plotly.plot block, but plotly never starts up and streams the data.
In some slightly more complex server code I was working on earlier, I also get the error which may or may not be related and which always points to the beginning of the plotly.plot block.
cb(null, body);
^
SyntaxError: Unexpected end of input
This is the full error stack:
/home/plotly-testing/node_modules/plotly/index.js:305
cb(null, body);
^
SyntaxError: Unexpected end of input
at Object.parse (native)
at /home/plotly-testing/node_modules/plotly/index.js:72:25
at IncomingMessage.<anonymous> (/home/plotly-testing/node_modules/plotly/index.js:305:9)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
---------------------------------------------
at IncomingMessage.Readable.on (_stream_readable.js:671:33)
at parseRes (/home/plotly-testing/node_modules/plotly/index.js:304:9)
at ClientRequest.<anonymous> (/home/plotly-testing/node_modules/plotly/index.js:71:9)
at ClientRequest.emit (events.js:107:17)
at HTTPParser.parserOnIncomingClient (_http_client.js:426:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at TLSSocket.socketOnData (_http_client.js:317:20)
---------------------------------------------
at new ClientRequest (_http_client.js:93:10)
at Object.exports.request (http.js:49:10)
at Object.exports.request (https.js:136:15)
at Plotly.plot (/home/plotly-testing/node_modules/plotly/index.js:70:21)
at Object.<anonymous> (/home/plotly-testing/index.js:175:8)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
Line 305 of plotly/index.js points to the following method, which seems to indicate something was wrong in one of my callbacks, but I'm not sure.
// response parse helper fn
function parseRes (res, cb) {
var body = '';
if ('setEncoding' in res) res.setEncoding('utf-8');
res.on('data', function (data) {
body += data;
if (body.length > 1e10) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ
res.connection.destroy();
res.writeHead(413, {'Content-Type': 'text/plain'});
res.end('req body too large');
return cb(new Error('body overflow'));
}
});
res.on('end', function () {
cb(null, body);
});
}
So I've modified the code to include a console.log inside the Plotly.plot callback.
See gist here:
https://gist.github.com/alexander-daniel/b36f9be78abbbaa4847e#file-index-js-L33
And that way we can see that Plotly returned a graph URL that we can look at.
https://gist.github.com/alexander-daniel/b36f9be78abbbaa4847e#file-console_output-L5
That should resolve the first issue.
As far as the second issue goes, it seems the problem is two fold:
- JSON.parse calls inside the library are not wrapped in try/catch, so it looks like if the stream-server returns anything that is not JSON, this will break.
We're looking into the streaming-server error returns, but I have opened this issue here re: the try/catch blocks in the API library.
github.com/plotly/plotly-nodejs/issues/37

Categories

Resources