I want to handle both JSON- and XML-type requests, so I am using body-parser-xml in my node application.
My problem is the second XML element is not binding to req.body, but I get the first element value instead.
My code is:
var loopback = require('loopback');
var boot = require('loopback-boot');
var cfenv = require('cfenv');
var bodyParser = require("body-parser");
var cookieParser = require('cookie-parser');
require('body-parser-xml')(bodyParser);
var app = module.exports = loopback();
var appEnv = cfenv.getAppEnv();
app.use(bodyParser.json());
app.use(bodyParser.xml({
limit: '1MB', // Reject payload bigger than 1 MB
xmlParseOptions: {
normalize: true, // Trim whitespace inside text nodes
normalizeTags: false, // Transform tags to lowercase
explicitArray: false // Only put nodes in array if >1
}
}));
app.use(bodyParser.urlencoded({
"extended": true
}));
// boot scripts mount components like REST API
boot(app, __dirname);
app.start = function() {
// start the web server
return app.listen(process.env.PORT || 3000, function() {
console.log("env port" + process.env.PORT);
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
My Routes:
module.exports = function(app) {
var router = app.loopback.Router();
var User = app.models.pusers;
var js2xmlparser = require("js2xmlparser");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
if (req.get("content-type") !== 'undefined') {
if (req.get("content-type") == 'application/json') {
res.setHeader('content-type', req.get("content-type"));
} else if (req.get("content-type") == 'application/xml') {
res.setHeader('content-type', req.get("content-type"));
}
}
next();
});
app.middleware('initial', function logResponse(req, res, next) {
res.on('finish', function() {});
req.on('end', function(data) {});
req.on('data', function(data) {
// the request was handled, print the log entry
console.log(req.method, req.originalUrl, res.statusCode);
if (req.get("content-type") == 'application/xml') {
console.log("xml data's :" + data);
} else if (req.get("content-type") == 'application/json') {
console.log("json data's :" + data);
}
});
next();
});
function responseHandler(req, res, data) {
if (req.get("content-type") == 'application/json') {
return JSON.stringify(data);
} else if (req.get("content-type") == 'application/xml') {
return js2xmlparser("response", JSON.stringify(data));
} else
return data;
}
router.post('/login', function(req, res) {
var response = {};
console.log(req.body);
console.log(req.body.username);
try {
User.find({
where: {
name: req.body.username
}
}, function(err, data) {
if (err) {
response = {
"error": true,
"message": "Error fetching data"
};
} else {
if (data.length != 0) {
if (data[0].name == req.body.username && data[0].password == req.body.password) {
response = {
"error": false,
"data": "Success"
};
} else {
response = {
"error": false,
"data": "Password is incorrect"
};
}
} else if (data.length == 0) {
response = {
"error": false,
"data": "Username is incorrect"
};
}
}
console.log("Check login");
res.end(responseHandler(req, res, response));
});
} catch (ex) {
console.error("Error while retrive all data from User Model by name", ex);
res.end(responseHandler(req, res, "Error while inserting User Model by name"));
}
});
app.use(router);
}
How can i solve this problem?
I found that if you encapsulate the whole data into a single XML tag, you receive the complete set. For example:
<data>
<username>somename</username>
<password>passwd</password>
</data>
Then access it in node.js as:
req_xml = req.body["data"];
console.log(req_xml["username"]);
console.log(req_xml["password"]);
Related
i cloned an node.js application and , to set up, i did an npm install and npm install -g nodemon , i wanted to run it locally on port 3000, so in my app.js file i added
app.listen(3000, () => console.log('Server running on port 3000!'))
and then i tried to run it by using node app.js but i am getting this errors
this is my app.js file
var express = require('express');
var engine = require('ejs-locals');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var request = require('request');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var routes = require('./routes/index');
var testgrid = require('./routes/testgrid');
var hsdes_query = require('./routes/hsdes_query');
var find_coverage = require('./routes/find_coverage');
var url = "mongodb://127.0.0.1:27017/onegrid_int";
var config = require('./config');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('ejs', engine);
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(fileUpload());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var manual_ti_payload_template = {
"attributes": [],
"blackList": "string",
"description": "string",
"endDate": "2019-02-03T21:28:12.567Z",
"id": "string",
"itemId": "string",
"key": "string",
"name": "ascii string",
"namespace": "ascii string",
"ownerIdsid": "string",
"planningAttributes": [],
"resources": [],
"resourcesVersions": [],
"startDate": "2019-02-03T21:28:12.567Z",
"type": "manualitem",
"version": 0,
"whiteList": "string"
}
app.post('/updategtaproc', function(req, res){
console.log("updategtaproc", req.body)
var username = "Lab_FMVPOSumit";
var password = "bdzxl12$";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
request.post( {
url : 'http://gta.intel.com/procedures/api/v1/procedures/' + req.body.name,
headers : {
"Authorization" : auth
},
json: {"description": req.body.description, "steps":req.body.steps}
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
res.send(body)
});
});
app.post('/createnupdategtaproc', function(req, res){
console.log("createnupdategtaproc", req.body)
var username = "Lab_FMVPOSumit";
var password = "bdzxl12$";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var ti_payload = Object.assign({}, manual_ti_payload_template);
ti_payload.name = req.body.expected;
ti_payload.description = req.body.description;
ti_payload.ownerIdsid = username;
ti_payload.namespace = "vtt-gve-gqe"
console.log(ti_payload)
request.post( {
url : 'https://gta.intel.com/api/tp/v1/testitems',
headers : {
"Authorization" : auth
},
json: ti_payload,
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
if (body && body.itemId) {
console.log("Test case created successfully", body.itemId);
var itemId = body.itemId;
request.post( {
url : 'http://gta.intel.com/procedures/api/v1/procedures/' + body.itemId,
headers : {
"Authorization" : auth
},
json: {"description": req.body.description, "steps":req.body.steps}
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
console.log("Test Procedure Uploaded Successfully");
body['itemId'] = itemId
res.send(body)
});
} else {
console.log("Failed to Create Test Case");
res.send({"message":"Failed To Create Test Case"})
}
});
});
app.post('/getgriditems/:id', function(req, res){
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid_int//getgriditems/:id unable to connect to mongodb')
}
else
{
var collection_name = (req.params.id).toLowerCase() + "-" + "griditems"
var collection = db.collection(collection_name);
var objectIdArr = [];
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
item = req.body[key];
try {
objectIdArr.push(ObjectId(String(item)));
}
catch (err)
{
// Invalid Object ID
}
}
}
collection.find({"_id" : {"$in" : objectIdArr }}).toArray(function(err, griditems) {
if(err)
{
console.log('onegrid//getgriditems/:id unable to get grid items')
}
else
{
var paths = []
for ( var r in griditems){
//console.log('path :', result[r]['path'])
paths.push(griditems[r]['path'].join(",") + ',' + griditems[r]['testItem']['itemId'])
}
console.log("paths", paths)
var global_result_collection = db.collection("onegrid-global-results");
global_result_collection.find({"full_path" : {"$in" : paths }}).toArray(function(err, results) {
if(err)
{
console.log('onegrid//getgriditems/:id unable to get test results')
}
else
{
var metadata = {}
metadata['griditems'] = griditems
metadata['results'] = results
console.log("test_results", results)
res.send(metadata);
db.close();
}
});
}
});
}
});
});
app.post('/get_all_tags', function(req, res){
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
var collection = db.collection('user_tags');
collection.find().toArray(function(err, tags) {
if(err)
{
console.log('onegrid/manual_tests/error getting documents from collection')
}
else
{
var tag_type_ar = tags.map(a => a.type_tag);
//console.log('onegrid/manual_tests/number_of_docs/', tests.length)
//console.log('onegrid/manual_tests/tags/', tags_name)
res.send(tag_type_ar);
db.close();
}
});
}
});
});
app.post('/getsettags', function(req, res){
//console.log('body: ' + JSON.stringify(req.body));
var url = "mongodb://127.0.0.1:27017/onegrid";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/getsettags/unable to connect to mongodb')
}
else
{
var objectId = ObjectId(req.body.id);
var collection = db.collection('gve_manual_testitems');
if(req.body.op == 'set_add') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to get test item id', objectId)
}
else
{
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
if(result['tags'] && result['tags'].indexOf(req.body.newtag) != -1) {
res.send(result);
db.close();
}
else {
if(result['tags'])
{
result['tags'].push(req.body.newtag)
}
else
{
result['tags'] = [req.body.newtag];
}
collection.updateOne({ _id : objectId }, { $set: { "tags" : result['tags'] } }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to set tags')
}
else
{
console.log('tags added successfully to test item');
var test_tags = result;
if(!req.body.skip_tag_source_update) {
var user_tags = db.collection('user_tags');
var type_tag = req.body.newtag;
var type = req.body.newtag.split(":")[0]
var tag = req.body.newtag.split(":")[1]
var tag_obj = {'type':type, 'tag': tag, 'type_tag' : type_tag}
user_tags.insertOne(tag_obj, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set unable to add to user tag')
}
else
{
console.log('tags added to user_tags')
res.send(test_tags);
db.close();
}
});
}
else
{
res.send(test_tags);
db.close();
}
//var newtag = req.body.newtag;
//var tag_type = newtag.split(":")[0];
//var tag_name = newtag.split(":")[1];
//console.log(tag_type,tag_name)
}
});
}
}
});
}
if(req.body.op == 'set_remove') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to get test item id', objectId)
}
else
{
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
result['tags'].splice(result['tags'].indexOf(req.body.newtag),1);
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
collection.updateOne({ _id : objectId }, { $set: { "tags" : result['tags'] } }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to set tags')
}
else
{
console.log('tags removed successfully')
//collection = db.collection('user_tags');
//var newtag = req.body.newtag;
//var tag_type = newtag.split(":")[0];
//var tag_name = newtag.split(":")[1];
//console.log(tag_type,tag_name)
res.send(result);
db.close();
}
});
}
});
}
if(req.body.op == 'get') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
//console.log('tags retrieved successfully ', result['tags'])
if(result['tags'])
res.send(result['tags'].join(","));
else
res.send("");
db.close();
}
});
}
}
});
});
app.post('/gettestprocs/:id', function(req, res){
console.log('gettestprocs body: ' + (req.body.itemId));
//var url = "mongodb://127.0.0.1:27017/og1";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
var collection_name = (req.params.id).toLowerCase() + "-" + "testprocs"
var collection = db.collection(collection_name);
collection.findOne({ "id" : req.body.itemId },function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
console.log('test proc:', result)
res.send(result);
db.close();
}
});
}
});
});
app.post('/gettestprocsbyitemid', function(req, res){
//console.log('gettestprocs body: ' + (req.body));
var url = "mongodb://127.0.0.1:27017/onegrid_int";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
console.log(req.body)
/*if(String(req.body.grid_type) == "MANUAL"){
collection_name = "n_gve_manual_testprocs"
} else if(String(req.body.grid_type) == "OLD_MANUAL") {
collection_name = "gve_manual_testprocs"
} else if(String(req.body.grid_type) == "SURFACE") {
collection_name = "gve_surface_testprocs"
}
else if(String(req.body.grid_type) == "AUTO") {
}*/
//var tp = testplans.filter(function(x){return x.itemId == req.params.id})[0];
var collection_name = (req.body.testplan_id).toLowerCase() + "-" + "testprocs"
var collection = db.collection(collection_name);
collection.findOne({"id" : String(req.body.proc_id) },function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
console.log('test proc:', result)
res.send(result);
db.close();
}
});
}
});
});
app.use('/', routes);
app.use('/testgrid', testgrid);
app.use('/hsdes_query', hsdes_query);
app.use('/find_coverage', find_coverage);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(3000, () => console.log('Server running on port 3000!'))
module.exports = app;
another app.js in C:\projects\New Project\onegrid\web\node_modules\ejs-locals\example
var express = require('express')
, engine = require('../')
, app = express();
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
// render 'index' into 'boilerplate':
app.get('/',function(req,res,next){
res.render('index', { what: 'best', who: 'me', muppets: [ 'Kermit', 'Fozzie', 'Gonzo' ] });
});
app.get('/foo.js', function(req,res,next){
res.sendfile('foo.js');
})
app.get('/foo.css', function(req,res,next){
res.sendfile('foo.css');
})
app.listen(3000);
what am i doing wrong , i just want to run it on localhost 3000. ?
Your terminal shows you running node server.js but your file is called app.js.
The Code works fine with the uncomment lines.
But when i activate the else Statement i get every times the 'not found' even there is a match between req.params.code and data.airports[i].code.
var express = require('express');
var data = require('./data.json');
var app = express();
app.use(express.static('public'));
app.set('view engine', 'jade');
app.get('/', function (req, res) {
res.render('index', { title: 'Startseite', message: 'index.html'});
});
app.get('/de-de/code/:code', function (req, res) {
for (var i in data.airports) {
if (req.params.code == data.airports[i].code) {
res.render('iata-code', data.airports[i]);
/* } else {
res.send('not found'); */
};
};
});
app.listen(80, function () {
console.log('Example app is running!');
});
Edit:
I change the code to:
app.get('/de-de/code/:code', function (req, res) {
for (var i in data.airports) {
if (req.params.code === data.airports[i].code) {
res.status(200).render('iata-code', data.airports[i]);
} else {
res.status(404).send({ error: 'Something failed!' });
};
};
});
even i send the http status code 404 before the headers i get the error in my console: Error: Can't set headers after they are sent.
Edit2:
app.get('/de-de/code/:code', function (req, res) {
for (var i in data.airports) {
if (req.params.code === data.airports[i].code) {
res.writeHead(200, { "Content-Type": "text/html" });
res.render('iata-code', data.airports[i]);
} else {
res.writeHead(404, { "Content-Type": "text/html" });
res.write('Something failed!');
res.end();
};
};
});
Edit3: I set up an alternative way. But this is also not working. I am New to node.js but i still dind't find a solution.
var express = require('express');
var data = require('./data.json');
var airports = data.airports;
var app = express();
function filterData (reqCode) {
var result = {};
for (var i in airports) {
console.log('-----');
console.log(i + ': ' + reqCode + ' <--> ' + airports[i].code);
console.log('-----');
if (airports[i].code === reqCode) {
result = airports[i];
} else {
result = {};
};
};
return result;
console.log(result);
};
app.get('/de-de/:code', function (req, res, next) {
var reqCode = req.params.code;
if (filterData(reqCode) === {}) next('route');
else next();
}, function (req, res, next) {
res.write('200');
res.end();
});
app.get('/de-de/:code', function (req, res, next) {
res.write('404');
res.end();
});
app.listen(80, function () {
console.log('Example app is running! Cancel Server with CTRL + C');
});
Your else is inside the for loop, so whenever req.params.code == data.airports[0].code doesn't return true (first pass), it will return not found, instead of going through the next candidate.
You are sending response more than one that's why you are getting this issue.
Instead of res.send() you should use res.write() to send multiple responses.
res.send() sends entire HTTP response to the client includes headers and content even it ends the response.
And after that, you can't send anything.
Note:
After completing loop you can finally call the res.send() if it requires for you.
I'm trying to create a tic-tac-toe game and want to save the user data into a database, but my problem is that the router I want to do this with can't be reached, I get an 'Internal server error message(500)'.
Here is the index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Lab5' });
});
//check if server is online
router.get('/alive', function(req, res, next) {
res.send('alive');
});
router.post('/alive', function(req, res) {
//here I generate the next step for the game
});
//this route can't be reached
router.get('/db', function(res, req) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({}, {}, function(e, docs) {
res.send(JSON.stringify(docs));
});
});
//and this route can be reached
router.post('/db', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
var username = req.body.username;
var gameStatus = req.body.gameStatus;
try {
if(Object.keys(req.body).length !== 0 && JSON.stringify(req.body) !== JSON.stringify({})){
console.log("Data insert...");
collection.insert({
"username" : username,
"gameStatus" : gameStatus
}, function (err, docs) {
if(err) {
res.send("Error inserting data into database!");
}
});
}
} catch(err) {
console.log("Error in insert: " + err);
}
});
module.exports = router;
Here is the getDB.js:
function getDB() {
var xhttp = createRequest();
if(xhttp === null) {
alert("Ajax object not supported by your browser!");
}
else {
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText != null) {
var db = JSON.parse(xhttp.responseText);
console.log(db);
}
}
}
xhttp.open('GET', 'db', true);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send();
}
}
My problem is with
router.get('/db', function() {...});
and the
router.post('/db', function() {...});
works just fine, it inserts the sent data into database.
Any help would be appreciated!
Seems that you forgot to import the mongodb bindings for express.
https://www.npmjs.com/package/express-mongo-db
So I'm going through the node.js in action book and I'm currently trying to build the chat based application on the second chapter. However, I keep on getting the Unexpected token ILLEGAL when I try to run the HTTP server, but i don't seem to see anything wrong:
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
}
else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
}
else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
}
else {
send404(response);
}
});
}
}

var server = http.createServer(function(request, response) {
var filePath = false;
if (request.url == '/') {
filePath = 'public/index.html';
}
else {
filePath = 'public' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(3000, function() {
 console.log("Server listening on port 3000.");
});
You seem to have strange hidden characters in your code,
try this
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
}
else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
}
else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
}
else {
send404(response);
}
});
}
}
var server = http.createServer(function(request, response) {
var filePath = false;
if (request.url == '/') {
filePath = 'public/index.html';
}
else {
filePath = 'public' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(3000, function() {
console.log("Server listening on port 3000.");
});
So, I've been struggling with these for a couple of hours now. The session won't get sent to server when I use AJAX to POST something to the server, but it works fine without AJAX, like clicking links, logout, etc and this is makes me pulling my hair in frustration. Anyway, these are my codes:
var express = require('express'), // express 4
mongoskin = require('mongoskin'),
Busboy = require('busboy'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
mailer = require('nodemailer'),
compress = require('compression'),
morgan = require('morgan'),
ect = require('ect'),
suspend = require('suspend'),
MongoStore = require('connect-mongo')(session);
app.use(compress());
app.engine('.ect', renderer.render);
app.set('env', 'development');
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
app.use('/admin', session({
secret : 'qlauwork secret yo',
name : 'qlauworks.sess',
proxy : true,
rolling : true,
cookie : {
maxAge : 1000 * 60 * 60 * 6
},
store : new MongoStore({
db : 'qlauworks',
auto_reconnect : true,
defaultExpirationTime : 1000 * 60 * 60 * 6
}),
unset : 'destroy'
}));
// ... etc etc
app.post('/admin/login', function (req, res) {
var msg = {};
var busboy = new Busboy({ headers : req.headers });
busboy.on('field', function (fieldName, val) {
msg[fieldName] = val;
});
busboy.on('finish', function () {
suspend.run(function * () {
msg.password = crypto.createHash('whirlpool').update(SALT).update(msg.password).digest('hex');
var user = yield db.users.findOne({ username : msg.username, password : msg.password }, suspend.resume());
if (!user) {
return res.json({ error : 'Wrong username or password' });
}
// create session token
var token = yield crypto.randomBytes(32, suspend.resume());
token = token.toString('hex');
yield db.users.update({ username : msg.username }, { $set : { token : token } }, { upsert : true }, suspend.resume());
req.session.token = token;
res.redirect('/admin/forms');
}, function (err) {
if (err) {
console.log('login: ', err);
res.send('Server error');
}
});
});
req.pipe(busboy);
});
// this is the logout and forms, works just fine
app.get('/admin/logout', auth, function (req, res) {
suspend.run(function * () {
var token = req.session.token;
yield db.users.update({ token : token }, { $unset : { token : true } }, suspend.resume());
delete req.session.token;
req.session.destroy(function (err) {
if (!err) {
res.clearCookie('qlauworks.sess', { path : '/' });
res.redirect('/admin');
}
});
}, function (err) {
if (err) {
console.log('logout: ', err);
res.json({ error : 'Server error' });
}
});
});
app.get('/admin/forms', auth, function (req, res) {
res.send(formPage);
});
// and this is the auth middleware, could logout and moving around the admin page
// but req.session always undefined if comes from an AJAX request
function auth (req, res, next) {
suspend.run(function * () {
console.log(req.session);
console.log('=====================================================')
if (!req.session.token) {
return res.json({ error : 'Invalid token' });
}
var user = yield db.users.findOne({ token : req.session.token }, suspend.resume());
if (!user.username) {
return res.json({ error : 'Invalid token' });
}
next();
}, function (err) {
if (err) {
console.log('auth: ', err);
res.json({ error : 'Server error' });
}
});
}
and this is the client side
$.post('/api/item/new', elem, function (rep) {
thisForm.find('input[type="submit"]').attr('disabled', false);
if (rep.error) {
$('#alert-multi').removeClass('success').addClass('alert').text(rep.error);
} else {
$('#alert-multi').removeClass('alert').addClass('success').text('Success');
$('input[type="reset"]').click();
for (var i = 0; i < len; i++) {
$('#preview-multi' + i).attr('src', '');
$('#multi' + i).attr('data-image-src', '');
}
}
});
So, how do I solve this?
It looks like you mounted the session middleware on /admin but you're trying to call /api/item/view.
That won't work as using express.use(path, middleware) will invoke middleware only for requests whose req.url contains path.
Either mount the session middleware on / (by not using path parameter - simple express.use(middleware) will do), or change your ajax url to start with /admin (probably not something you want to do).