how to get the api result from middleware to routes - node.js

I just wanted to get the result from the API in the middle ware that apply to routes. i am using express js the res.locals.wallet doesn't have a value
var request = require('request');
module.exports = function(req, res, next) {
if(req.session.active){
res.locals.active = req.session.active;
res.locals.email = req.session.email;
// res.locals.wallet = req.session.wallet;
res.locals.admin = req.session.admin;
res.locals.cart = req.session.cart;
res.locals.partner = req.session.partner;
var data = {
user_id :req.session.user_id,
}
request.post({
url : 'https://api.sample.com/frontend/sample',
form : data,
}, function (error, response, body) {
var bodyJson = JSON.parse(body);
console.log(bodyJson);
res.locals.wallet = req.session.wallet; <----- HERES THE PROBLEM
next();
});
} else {
res.redirect("/login");
}
next();
};

You call next immediate in your middleware, now res.locals.wallet value is undefined.
Just call next when you finish the job (call api).
var request = require('request');
module.exports = function(req, res, next) {
if(req.session.active){
res.locals.active = req.session.active;
res.locals.email = req.session.email;
// res.locals.wallet = req.session.wallet;
res.locals.admin = req.session.admin;
res.locals.cart = req.session.cart;
res.locals.partner = req.session.partner;
var data = {
user_id :req.session.user_id,
}
request.post({
url : 'https://api.sample.com/frontend/sample',
form : data,
}, function (error, response, body) {
var bodyJson = JSON.parse(body);
console.log(bodyJson);
res.locals.wallet = req.session.wallet; <----- HERES THE PROBLEM
next();
});
} else {
res.redirect("/login");
}
// next(); <----------------- remove this line
};

Related

The endpoints that are created with node.jsdoes not work properly?

I have a 2 different endpoint in index.js file. The android app calls and retrieves data with these endpoints from local MongoDB database. The first endpoint "/AddArac" works fine in starting but if ı Call "/AddArac" after calling "/ListArac" it gives an error.
For example:
/AddArac - /ListArac => this order is ok for both.
/ListArac - /AddArac => this order is not ok for /AddArac.
var mongodb = require('mongodb');
var objectID = mongodb.ObjectID;
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
var mongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017'
app.post('/AddArac', (request, response, next) => {
mongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
var db = client.db('basaranSMSDev');
var data = request.body;
var name = data.name;
var plaka = data.plaka;
var tel = data.tel;
var json = { 'name': name, 'plaka': plaka, 'tel': tel };
db.collection('Araclar').find({ 'plaka': plaka }).count(function (error, number) {
if (number > 0) {
response.json('Araç daha önce kaydedilmiş.');
}
else {
db.collection('Araclar').insertOne(json, function (error, res) {
if (err) {
res.json('Araç kaydında hata oluştu tekrar deneyiniz.');
console.log('Arac eklenemedi', err);
}
else {
res.json('Araç eklendi');
console.log('Arac eklendi.');
}
});
}
client.close();
});
});
});
app.get('/ListArac', (req, res) => {
mongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
var db = client.db('basaranSMSDev');
var items = db.collection('Araclar').find().toArray();
items.then(function (result) {
console.log(result)
res.json(result)
})
console.log(items);
client.close();
});
})
The error:
C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\utils.js:106
throw err;
^
TypeError: res.json is not a function
at C:\Users\Dilber\Basarannodejs\index.js:138:29
at executeCallback (C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\operations\execute_operation.js:70:5)
at C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\operations\insert_one.js:34:21
at handleCallback (C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\utils.js:102:55)
at C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\operations\common_functions.js:269:5
at C:\Users\Dilber\Basarannodejs\node_modules\mongodb\lib\core\connection\pool.js:405:18
at processTicksAndRejections (node:internal/process/task_queues:75:11)
in your code
app.post('/AddArac', (request, response, next) => {
you have used response as the response parameter.
but you used res in
if (err) {
res.json('Araç kaydında hata oluştu tekrar deneyiniz.');
res is not a function in
db.collection('Araclar').insertOne(json, function (error, res) {

Node.js endpoint is not working but another one is working

I have 2 endpoints in Node.js index.js file.
First one is working well and it turns 200 OK. But the second one is not working, it turns 404 Error. I could not find the reason.
First endpoint is /AddArac. It works well and adds data to MongoDB database
Second endpoint is /AddMesaj. It doesn't work. Both endpoints have the same logic.
My nodejs file is here:
`
var mongodb = require('mongodb');
var objectID = mongodb.ObjectID;
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
var mongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017'
mongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
if (err) {
console.log('Connection Fail', err);
}
else {
var db = client.db('basaranSMSDev');
//Add arac
app.post('/AddArac', (request, response, next) => {
var data = request.body;
var name = data.name;
var plaka = data.plaka;
var tel = data.tel;
var json = { 'name': name, 'plaka': plaka, 'tel': tel };
db.collection('Araclar').find({ 'plaka': plaka }).count(function (error, number) {
if (number > 0) {
response.json('Araç daha önce kaydedilmiş.');
}
else {
db.collection('Araclar').insertOne(json, function (error, res) {
if (err) {
response.json('Araç kaydında hata oluştu tekrar deneyiniz.');
console.log('Arac eklenemedi', err);
}
else {
response.json('Araç eklendi');
console.log('Arac eklendi.');
}
});
}
});
});
//Araç listesi getirme
//add mesaj
app.post('AddMesaj', (request, response, next) => {
var data_mes = request.body;
var plaka = data_mes.plaka;
var mtext = data_mes.text;
var driver = data_mes.driver;
var date = data_mes.tarih;
var json = { 'plaka': plaka, 'text': mtext, 'driver': driver, 'date': date };
db.collection('Mesajlar').insertOne(json, function (error, res) {
if (err) {
response.json('Mesaj gönderiminde hata oluştu tekrar deneyiniz.');
console.log('Mesaj eklenemedi', err);
}
else {
response.json('Mesaj gönderildi');
console.log('Mesaj eklendi.');
}
});
});
app.listen(3000, () => {
console.log('Connection ok');
});
//Mesaj listesi getirme
}
}
);
`
Change to:
app.post('/AddMesaj', (request, response, next) => {

handling session variables inside http.request in express

Hi. When i print the req.session.mySessValue in UI , the value is empty. I think the assigning of req.session.mySessValue = dt.myValue; (express-session) is not proper. could anyone help me on this. Thanks in advance.my express code is
router.get('/', function(req, res, next) {
if(!req.xx) {
return res.redirect('/firstView');
}
var options = {
.......
};
var call = http.request(options, function(resp) {
resp.on('data', function(dt) {
var jsondata = JSON.parse(dt);
req.session.mySessValue = dt.myValue;
});
});
call.end();
call.on('error', function(e) {
console.log("error" +e.message)
});
var v = {
title: 'sample',
req : req
}
res.render('myview', v);
});

node - continuation-local-storage

I am attempting to use the continuation-local-storage package to access the current express request/response from a point where that is not readily accessible.
I created the following middleware:
var createNamespace = require('continuation-local-storage').createNamespace,
getNamespace = require('continuation-local-storage').getNamespace;
const domain = 'ns.cls';
exports.configure = function(app) {
createNamespace(domain);
app.use(function(req, res, next) {
exports.set(req, res, "callcontext", { req, res });
next();
});
};
exports.set = function(req, res, name, value) {
var namespace = getNamespace(domain);
namespace.bindEmitter(req);
namespace.bindEmitter(res);
namespace.run(() => namespace.set(name, value));
};
exports.get = function(name) {
var namespace = getNamespace(domain);
return namespace.get(name);
};
exports.getCallContext = function() {
return exports.get("callcontext");
};
However when I attempt to access the context it is undefined:
var localStorage = require('../middleware/local-storage');
module.exports = function(doc, ctx) {
var callContext = localStorage.getCallContext();
console.log("value: " + callContext);
};
Does anyone have any ideas?
Thanks in advance,
Mark
createNameSpace should be called once. Also, you have an error on line
exports.set(req, res, "callcontext", { req, res });
should be something like
exports.set(req, res, "callcontext", { key: value });
This is the way I am using it:
to set
var session = require('continuation-local-storage').createNamespace('session')
app.use(function(req, res, next) {
session.bindEmitter(req);
session.bindEmitter(res);
session.run(function() {
session.set('req', req);
next();
});
});
to get
var session = require('continuation-local-storage').getNamespace('session')
session.get('req')

Kinvey Datasource and datalink mapping

If any one worked on Kinvey (Mbaas) Please help in setting up datalink project using nodeJS
I am new to nodeJS, I created an nodejs project based on kinvey sample.
Below is nodejs code sample
var configTools = require("./config");
var util = require("util");
var querystring = require('querystring');
var ServiceLink = require('./service_link');
var restify = require('restify');
var server = restify.createServer();
//Configure the server to parse the request body into req.body
server.use(restify.bodyParser({ mapParams: false }));
//insert into call chain when debugging
var debug = function(req, res, next) {
if (config.debug){
var method = req.method;
var params = req.params;
var query = req.query;
var body = req.body;
console.log("Method: " + method +
"\nParams: " + util.inspect(params, false, null, true) +
"\nQuery: " + util.inspect(query, false, null, true) +
"\nBody: " + util.inspect(body, false, null, true) + "\n");
}
if (config.debugFullRequest){
console.log(util.inspect(req));
}
return next();
}
// Verify key matches the header
var keyauth = function(req,res,next) {
var key = req.headers['x-auth-key'];
if (key != config.key) {
return next(new restify.InvalidCredentialsError("Invalid API Key"));
} else {
next();
}
}
//Router functions
var extractReq = function(req, next){
if (!req){ return new restify.InternalError("ServiceLink is having problems..."); }
var params = req.params;
var query = req.query;
var body = req.body;
var output = {query: null, params: null, body: null, route: null};
// Extract query
if (query && query !== undefined){
try {
var parsedString = querystring.parse(query);
output["query"] = JSON.parse(parsedString.query);
} catch (e){
return new restify.InvalidContentError("JSON query exception: " + e);
}
}
// Extract route
if (params && params !== undefined){
try {
var s = "";
s = params.collection;
if (params.id){
s = s + "/" + params.id;
}
output["route"] = s;
} catch (e){
return new restify.InvalidContentError("Invalid Params: " + e);
}
}
// Extract body
if (body && body !== undefined){
try {
output["body"] = body;
} catch (e){
return new restify.InvalidContentError("JSON body exception: " + e);
}
}
return output;
};
var preGet = function(req, res, next){
var data = extractReq(req, next);
if (data instanceof Error){
return next(data);
}
ServiceLink.get(data["route"], data["query"], data["body"], res, next);
};
server.get(/\/public\/?.*/, restify.serveStatic({
directory: './docs',
default: 'index.html'
}));
//For debugging we add in the debug middleware
server.get('/:stateList', keyauth, debug, preGet);
server.listen(3000, function() {
console.log('%s listening at %s', server.name, server.url);
});
if you look at the code, i have created angular front end and supply index page for routing.
my html file is loading fine, in that i will call kinvey datastore i.e stateList
like this
var promise = $kinvey.DataStore.find('stateList');
but it is giving me 500 error, when I mapped collection with datalink it is giving me error saying "_count endpoint to be implemented in the data link connector"
My datalink link is http://localhost:3000/
anyone please guide me on this mapping.
Thanks

Resources