Some of my routes don't work in express - javascript

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

Related

Port Errors running node.js application

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.

Node.js SELECT*FROM a table in a SQL database

My problem is that I can enter data from my input boxes into an SQL table, but the problem is that the text from the table will not show on the page i want to. What works is that the playlist page will show the a href links depending on how many playlists i have made just not the text.
I have left out the database details for security reasons.
playlist.jade
extends layout
block content
h1= title
p Welcome to #{title}
h1 My Playlists
br
a(href='/login') Login
br
a(href='/users/createPlaylist') Create a new Playlists
br
a(href='/users/playlistCreated') test
br
for playlist, i in playlists
a(href='/users/playlistCreated') | #{playlist.text}
br
users.js
var express = require('express');
var mysql = require('mysql');
var router = express.Router();
var dbConnectionInfo = {
host : '',
user : '',
password : '',
database : 'audio_collections'
};
router.get('/createPlaylist', function(req, res, next) {
res.render('new_playlist');
});
router.get('/playlistCreated', function(req, res, next) {
res.render('name_of_created_playlist');
});
router.get('/songCreated', function(req, res, next) {
res.render('song_page');
});
router.get('/newSong', function(req, res, next) {
res.render('new_song');
});
router.post('/newPlaylist', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
var playlist = {
text: req.body.thePlaylist
};
dbConnection.query('INSERT INTO Playlists (playlist_name) VALUES(?)', [playlist.text], function(err, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
if (err) {
throw err;
}
// notice that results.insertId will give you the value of the AI (auto-increment) field
playlist.id = results.insertId;
// Going to convert my joke object to a JSON string a print it out to the console
console.log(JSON.stringify(playlist));
// Close the connection and make sure you do it BEFORE you redirect
dbConnection.end();
res.redirect('/');
});
router.post('/newSongAdded', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
var song = {
text: req.body.theSong,
url: req.body.theSongURL
};
dbConnection.query('INSERT INTO Songs (song_name, song_url) VALUES(?,?)',[song.text, song.url], function(err, results,fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
if (err) {
throw err;
}
// notice that results.insertId will give you the value of the AI (auto-increment) field
song.id = results.insertId;
// Going to convert my joke object to a JSON string a print it out to the console
console.log(JSON.stringify(song));
// Close the connection and make sure you do it BEFORE you redirect
dbConnection.end();
res.redirect('/');
});
});
});
module.exports = router;
index.js
var express = require('express');
var mysql = require('mysql');
var router = express.Router();
var dbConnectionInfo = {
host : '',
user : '',
password : '',
database : 'audio_collections'
};
/* GET home page. */
router.get('/login', function(req, res, next) {
res.render('login');
});
router.post('/login', function(req, res, next) {
var username = req.body.username;
username = username.trim();
if (username.length == 0) {
res.redirect('/login');
}
else {
req.session.username = username;
res.redirect('/');
}
});
router.get('/', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
dbConnection.query('SELECT * FROM Playlists', function(err, results, fields){
if (err) {
throw err;
}
var allPlaylists = new Array();
for (var i = 0; i < results.length; i++) {
var playlist = {
id: results[i].id,
text: results[i].text
};
console.log(JSON.stringify(playlist));
allPlaylists.push(playlist);
}
dbConnection.end();
res.render('playlists', {playlists: allPlaylists});
});
router.get('/users/playlistCreated', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
dbConnection.query('SELECT * FROM Songs', function(err, results, fields){
if (err) {
throw err;
}
var allSongs = new Array();
for (var i = 0; i < results.length; i++) {
var song = {};
song.id = results[i].id;
song.text = results[i].text;
song.url = results[i].url;
console.log(JSON.stringify(song));
allSongs.push(song);
}
dbConnection.end();
res.render('name_of_created_playlist', {songs: allSongs});
});
});
});
module.exports = router;
new_playlist.jade
extends layout
block content
form(method='POST', action='/users/newPlaylist')
div
label(for='thePlaylist') Name of Playlist
div
textarea(type='text', name='thePlaylist')
br
input(type='submit', name='Add new Playlist')
a(href='/') Cancel
Here is the database and table setups
database and table setup
I would really appreciate the help and I have been stuck on this for a week now.
Got it fixed I didnt need the for loops inside my array
Only needed var allPlaylist = results; Since results is an array already

node js express - querying the price field

Im having trouble figuring out how to query the price. My current attempt is not working and im not sure what you have to type in the local host.
http://localhost:3000/priceSearch?
I have implemented - orderSearch.find({price:{$gt:400, $lt: 700}})
the price field in my mongodb is a number not a a string
Thank you:D
Here is my code:
priceSearch.ejs
var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/WishList';
router.get('/', function (req, res) {
var price = req.query.price;
MongoClient.connect(url, function (err, db) {
if (err) {
console.log("Unable to connect to the server", err);
} else {
console.log("Connection established...");
var orderSearch = db.collection('orders');
// find document who satisify price
orderSearch.find({price:{$gt:400, $lt: 700}}).toArray(function (err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.render('priceSearch',
{
priceSearch: result,
title: 'Product price search',
}
);
} else {
res.send("No documents found");
}
db.close();
});
}
});
});
module.exports = router;
req.query.price;
i added a stupid var to it

Can't export user data in node.js using MongoDB

I can't seem to find a way to export the user data that I get back from the database. When I require it in the other file I get undefined value or empty object. Please help all I want is to export the user info so I can use it in another file.
My auth.js file:
// Modules
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/affinity';
window.$ = window.jQuery = require('jquery');
$(document).ready(function () {
// Look through db for user
// Flters through the db to find the user and their password to authenticate them in.
userInfo = function (db, callback) {
var username = $('#username').val();
var password = $('#password').val();
var users = db.collection('users');
// Searches through each user in the db to find one which meets conitions.
var cursor = users.find({
"username": username
}, {"limit": 1} ).each(function (err, doc) {
if (doc != null) {
if (doc.password === password) {
module.exports.user_data = doc;
window.location.replace(__dirname + '/assets/views/main.html');
} else {
$("#error-hint").css(
'visibility', 'visible'
);
}
} else {
// Skip user if it isn't matching
}
});
}
// Connects to database.
// Inserts all user data to the database.
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Couldn\'t connect to the mongoDB server. \nERROR: ' + err);
} else {
var collection = db.collection('users');
// When login button run authUser function
$('#auth-btn').click(function () {
userInfo(db, function () {
db.close();
});
});
}
});
});
My app.js file:
// Modules
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/affinity';
var exported = require("/Users/mac/Desktop/projects/Affinity/assets/scripts/auth.js");
window.$ = window.jQuery = require('jquery');
$(document).ready(function () {
var userInfo = exported;
console.log(userInfo);
MongoClient.connect(url, function (err, db) {
if (err) {
console.log("Wasn't able to connect to mongoDB server. \n" + url);
} else {
console.log("Connection established to " + url);
db.close();
}
});
});
Thank you in advance!

Node JS body-parser-xml Not Working

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"]);

Categories

Resources