I am getting this error:
Cannot POST/.
Below is the code I'm trying to execute.
Server.js
var express = require('express');
var bodyParser = require('body-parser');
var _ = require('underscore');
var db = require('./db.js');
var bcryptjs = require('bcryptjs');
var middleware = require('./middleware.js')(db);
var http = require('http').Server(app);
var app = express();
var PORT = process.env.PORT || 3000;
var todos = [];
var todoNextId = 1;
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.send('Todo API Root');
});
app.get('/todos', middleware.requireAuthentication, function(req, res) {
var query = req.query;
var where = {
userId: req.user.get('id')
};
if (query.hasOwnProperty('completed') && query.completed === 'true') {
where.completed = true;
} else if (query.hasOwnProperty('completed') && query.completed === 'false') {
where.completed = false;
}
if (query.hasOwnProperty('q') && query.q.length > 0) {
where.description = {
$like: '%' + query.q + '%'
};
}
db.todo.findAll({
where: where
}).then(function(todos) {
res.json(todos);
}, function(e) {
res.status(500).send();
});
});
app.get('/todos/:id', middleware.requireAuthentication, function(req, res) {
var todoId = parseInt(req.params.id, 10);
db.todo.findOne({
where: {
id: todoId,
userId: req.user.get('id')
}
}).then(function(todo) {
if (!!todo) {
res.json(todo.toJSON());
} else {
res.status(404).send();
}
}, function(e) {
res.status(500).send();
});
});
app.post('/todos', middleware.requireAuthentication, function(req, res) {
var body = _.pick(req.body, 'description', 'completed');
db.todo.create(body).then(function(todo) {
req.user.addTodo(todo).then(function () {
return todo.reload();
}).then(function (todo) {
res.json(todo.toJSON());
});
}, function(e) {
res.status(400).json(e);
});
});
app.delete('/todos/:id', middleware.requireAuthentication, function(req, res) {
var todoId = parseInt(req.params.id, 10);
db.todo.destroy({
where: {
id: todoId,
userId: req.user.get('id')
}
}).then(function(rowsDeleted) {
if (rowsDeleted === 0) {
res.send(404).json({
error: 'No todo with id'
});
} else {
res.status(204).send();
}
}, function() {
res.status(500).send();
});
});
app.put('/todos/:id', middleware.requireAuthentication, function(req, res) {
var todoId = parseInt(req.params.id, 10);
var body = _.pick(req.body, 'description', 'completed');
var attributes = {};
if (body.hasOwnProperty('completed')) {
attributes.completed = body.completed;
}
if (body.hasOwnProperty('description')) {
attributes.description = body.description;
}
db.todo.findOne({
where: {
id: todoId,
userId: req.user.get('id')
}
}).then(function(todo) {
if (todo) {
todo.update(attributes).then(function(todo) {
res.json(todo.toJSON());
}, function(e) {
res.status(400).json(e);
});
} else {
res.status(404).send();
}
}, function() {
res.status(500).send();
});
});
app.post('/users', function(req, res) {
var body = _.pick(req.body, 'email', 'password');
db.user.create(body).then(function(user) {
res.json(user.toPublicJSON());
}, function(e) {
res.status(400).json(e);
});
});
app.post('/users/login', function (req, res) {
var body = _.pick(req.body, 'email', 'password');
var userInstance;
db.user.authenticate(body).then(function (user) {
var token = user.generateToken('authentication');
userInstance = user;
return db.token.create({
token: token
});
}).then(function (tokenInstance) {
res.header('Auth',
tokenInstance.get('token')).json(userInstance.toPublicJSON());
}).catch(function () {
res.status(401).send();
});
});
app.delete('/users/login', middleware.requireAuthentication,
function (req, res) {
req.token.destroy().then(function () {
res.status(204).send();
}).catch(function () {
res.status(500).send();
});
});
db.sequelize.sync({force: true}).then(function() {
app.listen(PORT, function() {
console.log('Express listening on port ' + PORT + '!');
});
});
This is my app.js file
app.post('/users', function(req, res) {
var body = _.pick(req.body, 'email', 'password');
db.user.create(body).then(function(user) {
res.json(user.toPublicJSON());
}, function(e) {
res.status(400).json(e);
});
});
I've been trying this but not getting through.Not sure whether the html file I have is correct. Want to create an html file to post from, but mine is refusing to respond.
You cannot POST to / because you haven't defined a route handler for POST requests to / (you only have one for GET to /).
Related
I am new to programming so I don't know why this happens. Users are reporting app crashes when logging in. The app is hosted on the Heroku platform with MongoDB. Can anyone tell me what the problem might be? P.S. I don't know if there is any other way to show the code, so I'll just paste it below. The user and password for the MongoDB connection string are changed for obvious reasons.
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const MongoClient = require("mongodb").MongoClient;
const app = express();
const uri =
"mongodb+srv://user:password#cluster0.4wwjt.mongodb.net/anketa?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.set("view engine", "ejs");
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("login");
});
app.get("/link", (req, res) => {
res.render("link");
});
app.get("/confirm", (req, res) => {
res.render("confirm");
});
app.get("/noMoreLinks", (req, res) => {
res.render("noMoreLinks");
});
app.post("/link", (req, res) => {
const username = req.body.username;
const password = req.body.password;
client.connect((err) => {
const users = client.db("anketa").collection("users");
const links = client.db("anketa").collection("links");
users.findOne({ user: username }, (err, foundUser) => {
if (err) {
console.log(err);
} else {
if (foundUser && foundUser.pass === password) {
const unvisitedLinksLength = foundUser.unvisitedLinks.length;
const currentTime = Date.now();
if (
foundUser.timeFinished &&
currentTime - foundUser.timeFinished < 18 * 60 * 60 * 1000
) {
res.render("comeTomorrow", {
headline: "Probajte opet za nekoliko sati",
});
return;
}
if (unvisitedLinksLength === 20) {
links.findOne({ id: 1 }, (err, foundLink) => {
if (err) {
console.log(err);
} else {
res.render("link", {
link: foundLink.path,
});
users.update(
{ user: foundUser.user },
{ $set: { currentLink: foundLink.id } }
);
}
});
return;
}
if (unvisitedLinksLength < 20 && unvisitedLinksLength > 0) {
let randomNumber = Math.floor(Math.random() * unvisitedLinksLength);
links.findOne(
{ id: foundUser.unvisitedLinks[randomNumber] },
(err, foundLink) => {
res.render("link", {
link: foundLink.path,
});
users.update(
{ user: foundUser.user },
{ $set: { currentLink: foundLink.id } }
);
}
);
return;
}
if (unvisitedLinksLength === 0 && foundUser.currentLink < 21) {
links.findOne({ id: foundUser.currentLink }, (err, foundLink) => {
res.render("link", {
link: foundLink.path,
});
});
return;
}
if (foundUser.currentLink === 0 && unvisitedLinksLength === 0) {
res.render("noMoreLinks");
return;
}
}
}
});
});
});
app.post("/confirm", (req, res) => {
const username = req.body.username;
client.connect((err) => {
const users = client.db("anketa").collection("users");
users.findOne({ user: username }, (err, foundUser) => {
const currentLinkId = foundUser.currentLink;
const unvisitedLinks = foundUser.unvisitedLinks;
const newUnvisitedLinks = unvisitedLinks.filter(
(linkId) => linkId !== currentLinkId
);
users.update(
{ user: foundUser.user },
{
$set: { unvisitedLinks: newUnvisitedLinks, timeFinished: Date.now() },
}
);
if (unvisitedLinks.length === 0) {
users.update({ user: foundUser.user }, { $set: { currentLink: 0 } });
return;
}
});
});
res.render("login");
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, () => {
console.log("server started successfully");
});
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.
I am creating an bill tracking application that is having users create bills based on criteria I have created using javascript.
I am tasked with performing acceptance testing.
This is my code so far:
My index.js file
const express = require('express')
const app = express()
const port = 3000
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bill');
var MongoClient = require('mongodb').MongoClient
var ObjectID = require('mongodb').ObjectID
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'))
app.set('view engine', 'pug')
app.set('views', __dirname + '/views');
var billSchema = new mongoose.Schema(
{
type: { type: String, required: true },
dueDate: { type: Date, required: true },
company: { type: String, required: true },
amtDue: { type: Number, required: true },
paidStatus: { type: String, required: true }
});
var bill = mongoose.model('bill', billSchema);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function()
{
app.get('/', (req, res) =>
{
bill.find({}, function(err, bills)
{
if (err)
{
console.log(err)
res.render('error', {})
}
else
{
res.render('index', { bills: bills })
}
});
});
app.get('/bills/new', (req, res) =>
{
res.render('bill-form', { title: "New bill", bill: {} })
});
app.get('/bills/:id/update', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.findById(id, function(err, bill)
{
if (err)
{
console.log(err)
res.render('error', {})
}
else
{
if (bill === null) {
res.render('error', { message: "Not found" })
} else {
res.render('bill-form', { title: "Update bill", bill: bill })
}
}
});
});
app.post('/bills/new', function(req, res, next) {
let newbill = new bill(req.body);
newbill.save(function(err, savedbill)
{
if (err)
{
console.log(err)
res.render('bill-form', { bill: newbill, error: err })
}
else
{
res.redirect('/bills/' + savedbill.id);
}
});
});
app.get('/bills/:id', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.findById(id, function(err, bill)
{
if (err)
{
console.log(err)
res.render('error', {})
}
else
{
if (bill === null)
{
res.render('error', { message: "Not found" })
}
else
{
res.render('bill-detail', { bill: bill})
}
}
});
});
app.post('/bills/:id/update', (req, res, next) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.updateOne({"_id": id}, { $set: req.body }, function(err, details)
{
if(err)
{
console.log(err)
res.render('error', {})
}
else
{
res.redirect('/bills/' + id)
}
});
});
app.post('/bills/:id/delete', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.deleteOne({_id: id}, function(err, product)
{
res.redirect("/")
});
});
app.post('/api/bills', (req, res) =>
{
let newbill = new bill(req.body)
newbill.save(function (err, savedbill)
{
if (err)
{
console.log(err)
res.status(500).send("There was an internal error")
}
else
{
res.send(savedbill)
}
});
});
app.post('/api/bills', (req, res) =>
{
bill.find({}, function(err, bills)
{
if(err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
res.send(bills)
}
});
});
app.get('/api/bills', (req, res) =>
{
bill.find({}, function(err, bills)
{
if(err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
res.send(bills)
}
});
});
app.get('/api/bills/:id', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.findById(id, function(err, bill)
{
if (err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
if (bill === null)
{
res.status(404).send("Not found")
}
else
{
res.send(bill)
}
}
});
});
app.put('/api/bills/:id', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.updateOne({"_id": id}, { $set: req.body }, function(err, details)
{
if (err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
res.status(204).send()
}
});
});
app.delete('/api/bills/:id', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
Review.deleteOne({"_id": id}, function(err)
{
if (err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
res.status(204).send()
}
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
module.exports.app = app;
module.exports.schema = bill;
Then I have a javscript dedicated to testing
let assert = require('assert');
let chai = require('chai');
let chaiHttp = require('chai-http');
let serverAndSchema = require('../index');
let server = serverAndSchema.app
let Bill = serverAndSchema.schema
let should = chai.should();
chai.use(chaiHttp);
describe('Bills', function() {
describe('/GET bill', function() {
it('should get the specified bill', function(done) {
let expectedBill = new Bill({
type: "Test Type",
dueDate: "12/3/2018T06:00:00.000Z",
company: "Test Company",
amtDue: "100",
paidStatus: "Test Status"
});
expectedBill.save(function(err, savedBill) {
chai.request(server)
.get('/api/bills/'+savedBill.id)
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('type').eql(savedBill.type)
res.body.should.have.property('dueDate').eql(savedBill.dueDate)
res.body.should.have.property('company').eql(savedBill.company)
res.body.should.have.property('amtDue').eql(savedBill.amtDue)
res.body.should.have.property('paidStatus').eql(savedBill.paidStatus)
res.body.should.have.property('_id').eql(savedBill.id)
done();
})
});
});
});
});
The data is added to my database, but I get this error when I try to run the test:
Uncaught TypeError: Cannot read property 'id' of undefined
at
C:\Users\Martae\Documents\Github\BillTracker\test\bill.js:29:46
Any help with this is appreciated!
When I checked the Bill schema, I found that the issue is caused by your due date format. So, the mongo saved is failed and you got undefined for savedBill and when you try to access id, it throws the error that you got.
Here is the solution:
let expectedBill = new Bill({
type: "Test Type",
dueDate: "2018-03-13T06:00:00.000Z", // change date to standardized format
company: "Test Company",
amtDue: "100",
paidStatus: "Test Status"
});
expectedBill.save(function(err, savedBill) {
const id = savedBill._id; // store id, it is always returned as _id
chai.request(server)
.get('/api/bills/'+id)
.end((err, res) => {
// ...
done();
});
});
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"]);
I'm writing an express app that uses socket.io; however all I'm getting is the sever side telling me I'm connected, aside from that, none of my sockets are working. If anyone can tell as to why this is happening that would be greatly appreciated. Here is my code for client and server below:
Client:
var socket = new io.Socket();
socket.connect('127.0.0.1:3000');
var pageView = new pageViewModel();
pageView.setCurrentPage(pageView.getLogin());
pageView.setNav(pageView.getLogNav());
var tView = new totalViewModel();
socket.on('connection', function () {
ko.applyBindings(pageView);
function loggedIn(e) {
e.preventDefault();
var logged = {
username: document.getElementById('pEmail').value,
password: document.getElementById('pWord').value
};
socket.emit('login', JSONout(logged));
alert(JSONout(logged));
}
function signUp() {
pageView.setCurrentPage(pageView.getRegister());
pageView.setNav(pageView.getRegisterNav());
ko.applyBindings(pageView);
}
socket.on('uploadList', function (data) {
pageView.setCurrentPage(pageView.getIndex());
pageView.setNav(pageView.getIndexNav());
ko.applyBindings(pageView);
tView.setNum(JSONin(data).total);
ko.applyBindings(tView);
});
function logPurchase(e) {
e.preventDefault();
var purchObj = {
price: document.getElementById('pPrice').value,
priceName: document.getElementById('pName').value,
entryDate: new Date()
};
socket.emit('purchaseLog', JSONout(purchObj));
}
function logDeposit(e) {
e.preventDefault();
var depositObj = {
price: document.getElementById('dPrice').value,
entryDate: new Date()
};
socket.emit('depositLog', JSONout(purchObj));
}
function getLogout(e) {
e.preventDefault();
pageView.setCurrentPage(pageView.getLogin());
pageView.setNav(pageView.getLogNav());
ko.applyBindings(pageView);
socket.emit('goLogout', {
none: 'none'
});
}
function getIndex(e) {
e.preventDefault();
pageView.setCurrentPage(pageView.getIndex());
pageView.setNav(pageView.getIndexNav());
ko.applyBindings(pageView);
}
function getMonthly(e) {
e.preventDefault();
pageView.setCurrentPage(pageView.getMonthly());
pageView.setNav(pageView.getMonthlyNav());
ko.applyBindings(pageView);
}
function getYearly(e) {
e.preventDefault();
pageView.setCurrentPage(pageView.getYearly());
pageView.setNav(pageView.getYearlyNav());
ko.applyBindings(pageView);
}
socket.on('wentMonth', function (data) {
tView.setNum(total in JSONin(data));
ko.applyBindings(tView);
});
socket.on('wentYearly', function (data) {
tView.setNum(total in JSONin(data));
ko.applyBindings(tView);
});
function register(e) {
e.preventDefault();
var reg = {
username: document.getElementById('pEmail').value,
password: document.getElementById('pWord').value,
dateJoined: new Date(),
total: 0,
purchase: {},
deposit: {},
monthlyTotal: 0,
yearlyTotal: 0
};
pageView.setCurrentPage(pageView.getIndex());
pageView.setNav(pageView.getIndexNav());
ko.applyBindings(pageView);
socket.emit('registered', JSONout(reg));
}
});
Server:
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var http = require('http');
var db = mongojs('127.0.0.1:27017/mySpendingDB', ['users']);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var path = require('path');
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', function (req, res) {
res.render('mainPage.html', {
title: 'app'
});
});
var user = "";
db.users.find(function (err, docs) {
console.log(docs);
return docs;
});
io.sockets.on('connection', function (socket) {
console.log('socket.io started');
socket.on('login', function (data) {
console.log('login');
var checkUser = db.users.find(data, function (err, docs) {
return docs;
});
console.log(checkUser);
if (checkUser !== null) {
console.log('checked user');
user = checkUser.username;
socket.emit('uploadList', checkUser.total);
} else {
console.log('Log in invalid');
}
});
socket.on('purchaseLog', function (data) {
var usercollection = db.users.find({
username: user
});
usercollection.purchase.save(data);
});
socket.on('depositLog', function (data) {
var usercollection = db.users.find({
username: user
});
usercollection.deposit.save(data);
});
socket.on('goMonthly', function (data) {
var monTot = db.users.find({
username: user
}).monthlyTotal;
socket.emit('wentMonthly', monTot);
});
socket.on('goYearly', function (data) {
var yearTot = db.users.find({
username: user
}).yearlyTotal;
socket.emit('wentYearly', yearTot);
});
socket.on('registered', function (data) {
db.users.save(data);
});
});
server.listen(3000);