I'm trying to get a polymer web page login to work but seemingly I can't since app.js cannot read the JSON database defined within the file itself. I have uploaded a screenshot of how my folders and files are layered in Visual Studio Code. I'm using a Windows 10 NT OS and Git Bash to run my commands.
THIS IS THE GIT BASH ERROR
Rhino#DESKTOP-NB42TJJ MINGW64
/c/users/rhino/documents/work/personal/polymer-project $ node
demo-server/app.js JSON Server is runnning TypeError: Cannot read
property 'users' of undefined
at C:\users\rhino\documents\work\personal\polymer-project\demo-server\app.js:34:33
at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5)
at next (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5)
at C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:277:22
at Function.process_params (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:330:12)
at next (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:271:10)
at C:\users\rhino\documents\work\personal\polymer-project\demo-server\app.js:29:9
at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5)
THIS IS MY app.js file
var express = require("../node_modules/express");
var app = express();
var path = require("path");
var jsonServer = require("../node_modules/json-server");
var server = jsonServer.create();
var router = jsonServer.router('db.json');
//Authentication Libraries - Start
var cookieParser = require('../node_modules/cookie-parser');
var session = require('../node_modules/express-session');
//Authentication Libraries - End
server.use(cookieParser("security", {"path": "/"}));
app.use(cookieParser("security", {"path": "/"}));
server.use(function(req, res, next) {
res.setHeader("Access
-Control-Allow-Origin", "http://localhost:8080");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
res.setHeader("Access-Control-Expose-Headers","Access-Control-Allow-Origin");
res.setHeader("Access-Control-Allow-Headers",
"X-Custom-Header,X-Requested-With,X-Prototype-Version,Content-Type,Cache- Control,Pragma,Origin,content-type");
if (!req.signedCookies.usersession && req._parsedUrl.pathname != "/auth/login" && req.method != "OPTIONS") {
res.redirect('http://localhost:8080/app/pages/auth/auth.html');
}else{
next();
}
});
server.post('/auth/login', function(req, res){
var users = router.db.object.users;
var username = req.query.username;
var password = req.query.password;
for(var i=0;i<=users.length -1;i++){
if(users[i].username == username && users[i].password == password) {
res.cookie('usersession', users[i].id, {maxAge: 9000000, httpOnly: false, signed: true});
res.send(JSON.stringify({success: true}));
return;
}
}
res.send(JSON.stringify({ success: false, error: 'Wrong username or password' }));
});
app.get('/', function(req, res){
if (!req.signedCookies.usersession) {
res.redirect('app/pages/auth/auth.html');
}else{
res.sendFile(path.join(__dirname+'/../app/index.html'));
}
});
app.get('/auth/logout', function(req, res){
res.clearCookie('usersession');
res.redirect('/app/pages/auth/auth.html');
});
/*app.get('/', function(req, res){
res.sendFile(path.join(__dirname+'/../app/index.html'));
});
*/
app.use(express.static(path.join(__dirname, '../')));
var http = require('http').Server(app);
http.listen(8080);
server.use(jsonServer.defaults); //logger, static and cors middlewares
server.use(router); //Mount router on '/'
server.listen(5000, function () {
console.log('JSON Server is runnning')
});
Picture of Visual Studio Code project folder structure
You may need to add middleware as follow in your code:
var jsonServer = require('../node_modules/json-server');
var server = jsonServer.create();
var router = jsonServer.router('db.json');
var middlewares = jsonServer.defaults(); //<--- new line
then in your server.use(jsonServer.defaults); //logger, static and cors middlewares, inject middleware as shown:
server.use(middlewares); //logger, static and cors middleware
Related
I try to configure the csurf node module for an API that does not use the cookie and session, but it has bearer token authentication.
Below is the code that is what i tried. When i run the below code and getting the below error
Error: misconfigured csrf
at csrf (/Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/csurf/index.js:71:19)
at Layer.handle [as handle_request] (/Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/router/index.js:317:13)
at /Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/router/index.js:335:12)
at next (/Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/router/index.js:275:10)
at expressInit (/Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/router/index.js:317:13)
at /Users/saravanan/Documents/Development/nodejs/csurf-demo-1/node_modules/express/lib/router/index.js:284:7
** Code Snippet **
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express();
app.use(csrf());
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.get('/form', function (req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', parseForm, function (req, res) {
res.send('data is being processed')
});
var PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
When I try with the below code that looks up for the header to validate the token, i am getting the error as cannot read session of undefined.
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({
value: (req) => {
var csrfToken = req.body._csrf || req.headers["x-csrf-token"];
return csrfToken;
},
cookie: false
})
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express();
app.use(csrfProtection());
app.get('/form', function (req, res) {
// pass the csrfToken to the view
// res.sendStatus(200);
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', parseForm, function (req, res) {
res.send('data is being processed')
});
var PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
How can the API be secured using either the auth token or via the csrf tokens?
please check:
The call to app.use(csrf()) must be set after app.use(cookieParser()) AND app.use(session({...}).
I've got into the same trouble. I don't have neither session nor cookies but JWT tokens. For now I am going to implement CSRF protection with jwt-csrf module. I think it is totally fit to my need and needs of topic starter.
I have a node server and an angularJS app.
I have a route to get informations about one record.
The route is '/pacientes/:id'
When I request data from that route i am getting an error.
What am I doing wrong?
//error:
Error: Can't set headers after they are sent.
at ServerResponse.setHeader (_http_outgoing.js:367:11)
at ServerResponse.header (C:\nodeapp\cloudapp\node_modules\express\lib\respo
nse.js:719:10)
at ServerResponse.send (C:\nodeapp\cloudapp\node_modules\express\lib\respons
e.js:164:12)
at ServerResponse.json (C:\nodeapp\cloudapp\node_modules\express\lib\respons
e.js:250:15)
at C:\nodeapp\cloudapp\server.js:973:10
at Array.forEach (native)
at C:\nodeapp\cloudapp\server.js:971:13
at Layer.handle [as handle_request] (C:\nodeapp\cloudapp\node_modules\expres
s\lib\router\layer.js:95:5)
at next (C:\nodeapp\cloudapp\node_modules\express\lib\router\route.js:131:13
)
at Route.dispatch (C:\nodeapp\cloudapp\node_modules\express\lib\router\route
.js:112:3)
Here is app controller:
angular.module("clinang").controller('ProcedimentosCtrl',['$scope','$http','$state',function($scope,$http,$state){
$scope.modelo={}
var tipoId=$state.params.tipoId;
if (tipoId) {
$http.get('/pacientes/' + tipoId).then(function(response){
$scope.modelo=response.data;
}, function(error){
console.log(error)
});
}
}]);
node - server.js
var express = require('express');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var path = require('path');
var app = express();
// Define the port to run on
app.set('port', process.env.port || 80);
app.use(bodyParser.json());
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
var pacientes=[
{id:1, nome:'Joao'},
{id:2, nome:'Maria'}
];
app.get('/pacientes/:id', function(req, res) {
pacientes.forEach(function (paciente) {
if (paciente.id == req.params.id) {
res.json(paciente);
return;
}
});
res.status(404).end();
});
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.status(404).end();
});
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
You are trying to send multiple responses to the same request from the client, but you can only send it once.
Change this:
pacientes.forEach(function (paciente) {
if (paciente.id == req.params.id) {
res.json(paciente);
return;
}
});
To this:
var result;
pacientes.forEach(function (paciente) {
if (paciente.id == req.params.id) {
result = paciente;
}
});
if (result !== undefined) {
res.json(result);
} else {
res.sendStatus(404);
}
The functions res.json, and res.sendStatus sets the header and the response's body, and call the .end() function after that, so you don't need to do it.
trying to implement authentication in my web-app using passport, passport-local and pasport-local-mongoose on node.js (using cloud9).
my authentication is successful, but when i'm trying to redirect to other page within my app (redirecting to http://www.google.com works!) i'm getting this stacktrace (need a direction on this):
TypeError: user.get is not a function
at /home/ubuntu/workspace/attendance/v4/node_modules/passport-local-mongoose/index.js:217:21
at pass (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:347:9)
at Authenticator.deserializeUser (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:352:5)
at SessionStrategy.authenticate (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/strategies/session.js:53:28)
at attempt (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/authenticate.js:348:16)
at authenticate (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/authenticate.js:349:7)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:312:13)
at /home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:330:12)
at next (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:271:10)
at initialize (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/initialize.js:53:5)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:312:13)
at /home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:330:12)
my app.js is the following:
var express = require('express'),
app = express(),
BodyParser = require("body-parser"),
mongoose = require("mongoose"),
students_class = require("./models/class"),
passport= require("passport"),
localstrategy=require ("passport-local"),
// passportlocalmongoose=("passport-local-mongoose"),
student = require ("./models/student");
mongoose.connect("mongodb://localhost/attendance");
app.set("view engine", "ejs");
app.use(express.static ("public"));
app.use(BodyParser.urlencoded({extended: true}));
app.use (require("express-session")( {
secret: "liran",
resave:false,
saveUninitialized:false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localstrategy(student.authenticate()));
passport.serializeUser(student.serializeUser());
passport.deserializeUser(student.serializeUser());
// ====
// routes
// =====
app.get("/", function(req, res) {
student.find({}, function(err, student) {
if (err) {
console.log(err);
} else {
res.render("home/index.ejs", {
students: student
});
}
});
});
app.post ("/login",passport.authenticate("local"),function (req,res) {
res.redirect("/");
})
and my user model:
var mongoose = require("mongoose"),
passportlocalmongoose=require("passport-local-mongoose")
var studentsSchema = new mongoose.Schema({
username: String,
passport:String
// name: String,
// image: String,
// description:String,
// classes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'class' }]
});
studentsSchema.plugin(passportlocalmongoose);
module.exports= mongoose.model("student", studentsSchema);
Let's check the stack trace to see if we can find a hint:
TypeError: user.get is not a function
at /home/ubuntu/workspace/attendance/v4/node_modules/passport-local-mongoose/index.js:217:21
at pass (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:347:9)
at Authenticator.deserializeUser (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:352:5)
...
Hmm, deserializeUser might be causing the problem.
Let's look at how it's set up:
passport.serializeUser(student.serializeUser());
passport.deserializeUser(student.serializeUser());
Perhaps you meant to pass student.deserializeUser() to passport.deserializerUser()?
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
mongoose.connect("mongodb://localhost/test");
var todoschema = new mongoose.Schema ({
name : {type: String, required: true}
});
var todomodel = mongoose.model('todolist',todoschema);
app.get('/',function(req,res){
res.sendFile('C:/Users/Rohit/Desktop/New folder/public/todo.html');
})
app.get('/todolist', function (req, res){
todomodel.find(function(err,tasks){
res.json(tasks);
});
});
app.post('/todolist', function (req, res) {
todomodel.insert(req.body, function(err, task) {
res.json(task);
});
});
app.delete('/todolist/:id', function (req, res) {
todomodel.remove(req.params.id, function (err, task) {
res.json(task);
});
});
app.get('/todolist/:id', function (req, res) {
todomodel.findById(req.params.id, function (err, task) {
res.json(task);
});
});
app.put('/todolist/:id', function (req, res) {
todomodel.findAndModify({
query: req.params.id,
update: {$set: {name: req.body.name}},
new: true}, function (err, task) {
res.json(task);
}
);
});
app.listen(3000);
console.log("Server running on port 3000");
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (C:\Users\Rohit\node_modules\express\lib\response.js:403:11)
at C:\Users\Rohit\Desktop\New folder\mong.js:17:9
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Rohit\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\Users\Rohit\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Rohit\node_modules\express\lib\router\index.js:277:22
at Function.process_params (C:\Users\Rohit\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Rohit\node_modules\express\lib\router\index.js:271:10)
at jsonParser (C:\Users\Rohit\node_modules\body-parser\lib\types\json.js:100:40)
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Rohit\node_modules\express\lib\router\index.js:312:13)
at C:\Users\Rohit\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Users\Rohit\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Rohit\node_modules\express\lib\router\index.js:271:10)
at expressInit (C:\Users\Rohit\node_modules\express\lib\middleware\init.js:33:5)
I tried to display a todo.html page by connecting to http://localhost:3000 , but I'm getting an error when i open the http://localhost:3000 page , the error i have uploaded above as a snippet. Can you please guide me on how to display the html file ?
res.sendFile("C:/Users/Rohit/Desktop/New folder/public/todo.html");
UPDATE
try to use
res.sendFile("C:\\Users\\Rohit\\Desktop\\New folder\\public\\todo.html");
#robin
look at the express source code, express/lib/utils.js
exports.isAbsolute = function(path){
if ('/' == path[0]) return true;
if (':' == path[1] && '\\' == path[2]) return true;
if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path
};
It only check the \\, i think it is a bug.
When i am trying to launch my nodejs server, it does not call the client/public folder. I get the below error, when i point to http://localhost:3000
Error: Not found at
/home/shankar/projects/apiDocs/server/server.js:36:12 at
Layer.handle [as handle_request]
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:312:13)
at
/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:280:7
at Function.process_params
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:330:12)
at next
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:271:10)
at
/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:618:15
at next
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:256:14)
at Function.handle
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:176:3)
at router
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:46:12)
Below is my server.js code
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(express.static(path.join(__dirname, "public")));
app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
mongoose.connect('mongodb://127.0.0.1:27017/app', function (error) {
if (error) {
console.log(error);
}
});
app.all('/*', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Access-Token,X-Key");
if(req.method === 'OPTIONS'){
res.status(200).end();
} else {
next();
}
});
app.all("/api/v1/*", [require('./middlewares/validateRequest')]);
app.use("/", require("./routes"));
app.use(function(req, res, next){
var err = new Error("Not found");
err.status = 404;
next(err);
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
I am trying to run my client and my restful services on same server, when i launch my server on port 3000, i expect the client and server to be on the same server.
Folder Structure:
/app
--node-modules
--public
--app //contains all angularjs related files
--assets //contains images and js libraries
--index.html
--server
--server.js
try to use this :
app.use(express.static('./.'));
this is should let express able to see your files