express parsing json with body-parse - node.js

I'm trying to use body-parse version 1.18.3 with express to parse a json post. In app.js I've included it like so
app.js
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
...
//App setup
var app = express();
// create application/json parser
var jsonParser = bodyParser.json()
app.set('trust proxy', 1) // trust first proxy
// Use the session middleware
app.use(session({ secret: 'secretletters', cookie: {}}))
app.post('/', jsonParser, function (req, res) {
console.log(req.body);
if (req.session.username) {
} else {
}
res.send({'status': 'ok'})
});
and in my script on the frontend send a username back to it
$('.login-btn').click(function() {
let username = $('.username').val();
if (username == '') {
$('.login-error').removeClass('hidden');
return null;
}
//if passed hide error
$('.login-error').addClass('hidden');
var data = {
'username': username
}
$.ajax({
url: "/",
type: "POST",
dataType: 'json',
data: JSON.stringify(data),
success: function(response){
},
error: function(xhr){
},
});
/* End Ajax Call */
});
It send the username successfully, here's a screenshot of the results of the post request from the network tools
the bug is when on console.log(req.body); on app.post I get back and empty {} dict

Related

How to authenticate keycloak token using node js that calls postgraphile?

I'm new on node js, and the company that i work for needs a proof of concept about postgraphile, the situation is this:
I created a node js mini server that uses postgraphile to access the data on postgres
The mini server works fine and can return data and also can use mutations.
I used keycloak-connect to try to access keycloak to authenticate the token from the request that is sent by postman but there is a problem.
If the token is valid or not it does not matter for the mini server, the only thing that seems to matter is that is a bearer token.
I tried to use other plugins (like keycloak-nodejs-connect, keycloak-verify, etc) but the result is the same, i also changed my code to use the examples in the documentation of those plugins but nothing.
This is my code: (keycloak-config.js file)
var session = require('express-session');
var Keycloak = require('keycloak-connect');
let _keycloak;
var keycloakConfig = {
clientId: 'type credential',
bearerOnly: true,
serverUrl: 'our company server',
realm: 'the test realm',
grantType: "client_credentials",
credentials: {
secret: 'our secret'
}
};
function initKeycloak(){
if(_keycloak){
console.warn("Trying to init Keycloak again!");
return _keycloak;
}
else{
console.log("Initializing Keycloak...");
var memoryStore = new session.MemoryStore();
_keycloak = new Keycloak({store: memoryStore}, keycloakConfig);
return _keycloak;
}
}
function getKeycloak(){
if(!_keycloak){
console.error('Keycloak has not been initialized. Please called init first');
}
return _keycloak;
}
module.exports = {
initKeycloak,
getKeycloak
};
My Index.js file:
const express = require('express')
const bodyParser = require('body-parser')
const postgraphile = require('./postgraphile')
const app = express()
const keycloak = require('../config/keycloak-config').initKeycloak()
var router = express.Router();
app.set( 'trust proxy', true );
app.use(keycloak.middleware());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(postgraphile);
app.get('/', keycloak.checkSso(), (req, res) => {
res.send('success');
} );
var server = app.listen(8080, () => console.log(`Server running on port ${8080}`));
Also I used this code to get the token and use the keycloak-verify plugin but got nothing:
router.get('/',keycloak.protect(),function(req, res, next) {
var token=req.headers['authorization'];
console.log(token);
try {
let user = keycloak.jwt.verify(token);
console.log(user.isExpired());
} catch (error) {
console.error(error);
}
})
I know that I lack the knowledge because I am a backend (C#) developer, can somebody help me with this?, thanks in advance.
I found the answer to my problem:
const express = require("express");
const request = require("request");
var keycloakConfig = require('../AuthOnly/config/keycloak-config').keycloakConfig;
const postgraphile = require('./postgraphile');
const app = express();
const keycloakHost = keycloakConfig.serverUrl;
const realmName = keycloakConfig.realm;
// check each request for a valid bearer token
app.use((req, res, next) => {
// assumes bearer token is passed as an authorization header
if (req.headers.authorization) {
// configure the request to your keycloak server
const options = {
method: 'GET',
url: `${keycloakHost}/auth/realms/${realmName}/protocol/openid-connect/userinfo`,
headers: {
// add the token you received to the userinfo request, sent to keycloak
Authorization: req.headers.authorization,
},
};
// send a request to the userinfo endpoint on keycloak
request(options, (error, response, body) => {
if (error) throw new Error(error);
// if the request status isn't "OK", the token is invalid
if (response.statusCode !== 200) {
res.status(401).json({
error: `unauthorized`,
});
}
// the token is valid pass request onto your next function
else {
next();
}
});
} else {
// there is no token, don't process request further
res.status(401).json({
error: `unauthorized`,
});
}});
app.use(postgraphile);
app.listen(8080);

req.body.variablename is undefined in express with body-parser middleware

I am using express 4.14.1 version in my Nodejs application. I am also using body parser middleware for parsing form data but when I write console.log(req.body.variablename) I get undefined on the console.
my code is as follows
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser'); //parses information from POST
const request = require('request');
const mongodb = require('../model/mongodb.js');
const smtpTransport = require('../model/mailer.js');
const Agent = require('../model/agentmodel.js');
const config = require('../config.js');
const intent = require('../intents.js');
const ejs = require('ejs');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// use res.render to load up an ejs view file
router.get('/chat', function(req,res){
// res.sendFile(path.join(__dirname + '/html/' + '/index.html'));
res.render('pages/index', { heading: config.property.userheading});
});
// use res.render to load up an ejs view file
router.get('/', function(req,res){
// res.sendFile(path.join(__dirname + '/html/' + '/index.html'));
res.render('pages/helpdesk');
});
router.post('/createTicket', function(req,res){
console.log("create ticket is called from email support");
console.log(req.body);
console.log("and the details as follows ==>");
console.log("username is ==> "+req.body.userName);
console.log("message is ==>"+req.body.message);
var json = {
name : req.body.userName,
email : req.body.userEmail,
subject: 'Demo Subject',
message: req.body.message,
topicId : req.body.topicId,
};
var options = {
url: 'http://domainname/iprhelpdesk/upload/api/http.php/tickets.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key' : 'API-key'
},
json:json
};
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
console.log("response is ==>");
console.log(res);
}
else {
console.log("error is "+err+ " = and reponse code is ="+res.statusCode );
}
});
res.render('pages/message');
});
following is the output of the console
create ticket is called from email support {
'{"topicId":{"Id":12,"name":"Basic IPR Query"},"message":"i want to
know about ipr","userName":"Pawan
Patil","country":"IN","userEmail":"pawanpatil.rocks#gmail.com","contact":"09665714555"}':
'' } and the details as follows ==> username is ==> undefined message
is ==>undefined POST /createTicket 200 21.161 ms - 104 error is null =
and reponse code is =400
and this is what chrome is sending as a form data
{"topicId":{"Id":12,"name":"Basic IPR Query"},"message":"i want to
know about ipr","userName":"Jon
Snow","country":"IN","userEmail":"test#test.com","contact":"0123456789"}:
Request header is
Content-Type:application/x-www-form-urlencoded
everything seems to be perfect but still, I am getting
undefined
when I write console.log("username is ==> "+req.body.userName); in my code.
please help me out
Move those:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Before this:
app.use(app.router)
So your bodyParser need to be initialized before the router. I also have read that using this:
app.use(require('connect').bodyParser());
Insted of:
app.use(express.bodyParser());
May also fix the problem with undefined req.body
And one more thing to try is:
app.use(bodyParser.urlencoded({ extended: false}));
Set extended to be false instead of true
I have solved the problem from changing
Content-Type:application/x-www-form-urlencoded
header to the
Content-Type: application/json

Does node.js support setting session with mutliple asynchronous HTTP calls?

In my node.js app , I'm setting the session using async calls. I have used express-session for the session management. But setting the session behaves occasionally. I'm calling the 2 node.js routes using an angular app.
First time it will call the HTTP get calls and get all the data correctly. But only the last delayed route data will be set to the session. Not data from both route. Seems like setting the data from the delayed route is replacing the fast route session data. Here's my code.
Sometimes all the data is set to the session. (After 2 browser refreshes)
var express = require('express');
var http = require('http');
var request = require('request');
var bodyParser = require('body-parser');
var session = require('express-session');
var ejs = require('ejs');
var cookieParser = require('cookie-parser'); // the session is stored in a cookie, so we use this to parse it
var app = express();
app.set('views', __dirname + '/views');
app.set('port', process.env.PORT || 8081);
app.use(express.static(__dirname + '/app/'));
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(cookieParser());
app.use(session({
secret: '232332dfdffd',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 3600000 }}))
app.engine('html', ejs.renderFile);
var server = app.listen(8081,function(){
});
app.get('/route1', function(req, res , next) {
var data1 = req.session.data1;
if(data1){
console.log("Session is not null. Getting data1 from session");
res.status(200);
res.send(data1);
}else{
request({
url: "testUrl",
qs: {},
json: req.body,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}, function(error, response, body){
if(error) {
console.log("error "+error);
res.sendStatus(error);
} else {
req.session.data1 = response;
res.status(response.statusCode);
res.send(response);
}
});
}
});
app.get('/route2', function(req, res , next) {
var data2 = req.session.data2;
if(data2){
console.log("Session is not null. Getting data2 from session");
res.status(200);
res.send(data1);
}else{
request({
url: "testUrl2",
qs: {},
json: req.body,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}, function(error, response, body){
if(error) {
console.log("error "+error);
res.sendStatus(error);
} else {
req.session.data2 = response;
res.status(response.statusCode);
res.send(response);
}
});
}
});

TypeError: undefined is not a function in node js

I am trying to get data from server and show it on web page but
I am getting a error at end of file
response.end(body);
TypeError: undefined is not a function
i don't get what the error is please help
My Nodejs Code
var express=require("express");
var app=express();
var request = require('request');
var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/service',function(req,res){
var id = req.query.name;
console.log('hi');
console.log(id);
request.post({
headers: {
//set header if needed
},
url : 'http://example.com:8080/rest/api/2/issue/id',
json : {
userName:'username',
password:'password'
}
},
function(error, response, body){
if(error) {
console.log(error);
} else {
response.end(body);
}
});
});
console.log('running');
app.listen(8082);
You want to use the res variable, which is the response object passed into your Express request handler:
res.end(body);
response is an object passed by the request library that you're using, which is a different thing.

NodeJS + ExpressJS User Login

I am currently working on a web application that requires an user login snippet. I have built an API for getting user information and others. But I cannot let NodeJS work with sessions.
So, I have an API endpoint like this for logging in: /api/v1/login
The other endpoints of the API works with an Authorization header that contains Token e3f0d20dae2da4e3f0d20dae2da4 value.
What I want to do is, when user not logged in, redirect them to login page and when an user gives their credentials POST JSON data to /api/v1/login and save the returning Token object from body and use it on other API calls.
Login endpoint returns this:
{"token" e3f0d20dae2da4e3f0d20dae2da4: , "user_id": 1104}
Well actually I have let people in and use that token for request but the problem that i am having is when there are two or more user, req.session value overrides to the latest user that logged in.
How can i let it work?
Thanks.
EDIT:
var express = require('express');
var session = require('express-session');
var router = express.Router();
var https = require('https');
var url = require('url');
var request = require('request');
var cookieParser = require("cookie-parser");
var FileStore = require('session-file-store')(session);
var sessionMW = session(
{
store: FileStore(),
secret: '$LSvj3KLSv2$$1!skv!!!!xxIf3eef5Fxc',
cookie: { maxAge: 36000, httpOnly: false },
resave: false,
saveUninitialized: false
});
router.get('/api/:endpoint/:first?/:second?/:third?', sessionMW, function(req, res, next) {
if(sess.token){
// make http request and return json data from server
} else {
// fail
}
router.post("/login", sessionMW, function(req, res, next){
var username = req.body.username;
var password = req.body.password;
var options = {
url: endpoints.login_request(),
method: 'POST',
json: {
"username" : username,
"password" : password
},
headers: {
'User-Agent' : 'Agent',
'Content-Type': 'application/json'
}
};
request(options, function(err, response, body) {
if(body.error){
res.send('{error:1}');
} else if(body.token) {
req.session.token = body.token;
req.session.user_id = body.user_id;
res.writeHead(302, {
'Location': '/#/home'
//add other headers here...
});
}
console.log(req.session);
res.end();
});
});

Resources