I'm newbie in Node.js and Express and I'm trying to generate a security token using CSURF module. First, I have made a test using the documentation of the module and with only one file, for example, index.js works fine, but then, I have to try to separate the code in two files index.js and routes-api.js and it doesn't work and I don't know why.
index.js
This file requires "routes-api.js"
//Creación de un servidor con express
const express = require("express");
const app = express(); //Inicializamos express
//Accedemos a otros módulos
const morgan = require("morgan");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
//Accedemos a propiedades de configuración
const config = require("./config");
//Rutas
const routes = require("./routes");
const routesAPI = require("./routes-api");
//Settings
app.set("app-name", config.server);
app.set("port", config.port);
app.set("super-secret", config.secret);
//Middlewares
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(morgan("dev")); //Log request to the console
app.use((req, res, next) => {
console.log("Pasamos por la segunda función!!!");
next();
});
//Routing
app.use("/api", routesAPI);
app.use(routes);
//Server
app.listen(app.get("port"), () => {
console.log("Servidor " + app.get("app-name") + " escuchando!!!");
});
routes-api.js
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var bodyParser = require('body-parser');
var express = require('express');
const path = require("path");
const app = express();
const router = express.Router();
// setup route middlewares
var csrfProtection = csrf({ cookie: true });
var parseForm = bodyParser.urlencoded({ extended: false });
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser());
router.get("/", csrfProtection, (req, res) => {
console.log("crsf: " + req.csrfToken());
res.sendFile(path.join(__dirname + '/send.html'), { csrfToken: req.csrfToken() });
});
module.exports = router;
So, what am I doing wrong in routes-api.js file to get a misconfigured csrf error?
It looks like there's a new app in routes-api.js that's different than the existing app in index.js?
Maybe the routesAPI module should export a function that adds a router to an app.
Related
GET request return 404 error but POST request to the same url works fine I could not figure out the reason.
this is the server setup:
images.route.js
const express= require('express');
const controllers = require('./controllers');
const router= express.Router();
const upload = require('../../lib/uploads.controller');
router.get('/', (req, res)=> res.send('get request'))
router.post('/', controllers.getAll);
module.exports= router;
route.js
const express = require('express'),
router = express.Router();
const albumRoutes = require('./albums/album.route');
const imageRoutes= require('./images/index');
router.use('/albums', albumRoutes);
router.use('/images', imageRoutes);
module.exports= router;
server.js
let express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser');
let history = require('connect-history-api-fallback');
const userRoute = require('./routes/router');
const app = express();
app.options('*', cors())
app.use(cors());
app.use(history());
app.use(express.json({limit:
'50mb'}));
app.use(express.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 1000000
}));
app.use('/api', userRoute)
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log('Connected to port ' + port)
})
I have been searching for a solution but I could not find any reason.
I even installed different REST API apps like postman and insomnia just in case, but it is the same
I am using router in my NodeJs app.When I am trying to navigate it is unable to navigate to the given page.
Register.js is placed in routes folder and server.js is placed in parent directory.
Here is my code:
Server.js
const express = require('express');
const app = express();
app.set('view engine','ejs');
app.use(require('./routes/register'));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
var app = express();
router.use(bodyParser.json);
router.use(bodyParser.urlencoded({extended:true}));
router.get('/users', (req,res) => {
console.log('Hello there');
});
module.exports = router;
Now when I run this code and go to localhost:3000/users nothing happens and not even error shows in console.
Please let me know what I am doing wrong in above code.
Use router.use(bodyParser.json()); in register.js.
You have used body-parser at wrong place. Also you should initiate those with express instances always.
Also check your file name you have imported. Reigster -> register
Updated code:
Server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine','ejs');
app.use(require('./Register'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
router.get('/users', (req,res) => {
console.log('Hello there');
res.sendStatus(200)
});
module.exports = router;
I have an app where I am trying to move the routes to separate files. I keep getting a CANNOT GET/ when trying to use express router. I've set it up the same way I have it in other apps but can't get it to work.
this is in my routes folder: index.js
var express = require('express');
var router = new express.Router();
var Blog = require('../models/blogpost');
var User = require('../models/user');
var passport = require('passport');
router.get("/", function(req, res){
Blog.find({}, function(err, blogs){
if(err){
console.log(err);
} else {
res.render("index", {blogs: blogs});
}
});
});
module.exports = router;
This is my app.js file:
var methodOverride = require('method-override'),
LocalStrategy = require('passport-local'),
bodyParser = require('body-parser'),
nodeMailer = require('nodemailer'),
passport = require('passport'),
mongoose = require('mongoose'),
express = require('express'),
request = require("express"),
router = express.Router(),
User = require('./models/user'),
Blog = require('./models/blogpost'),
Comment = require('./models/comment'),
middleware = require('./middleware'),
app = express(),
request = require('request'),
indexRoutes = require('./routes/index');
//==================================
//APP CONFIG
//==================================
// mongoose.connect("mongodb://localhost/amy_blog");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});
app.use(express.static(__dirname + "/public"));
app.use('/', indexRoutes);
=====================
app.listen(process.env.PORT, process.env.IP, function(){
console.log("================================");
console.log("The Blog server has started!");
console.log("================================");
});
Any help would be greatly appreciated. Been racking my mind about this one for awhile.
You don't want to be creating a new instance of express.Route().
In your routes file remove the new keyword from where you assign the router variable. Probably just a typo.
As per the docs https://expressjs.com/en/guide/routing.html
express.Router() instance is a middleware and routing system for Express.js. In your code, there are two mistakes you are making:
Calling express.Router() with the new keyword
Not loading the router module in the app
Below is a simple approach you can use to make your application work:
const express = require('express');
const app = express();
const router = express.Router();
// This route handler is for demo purposes,
// you can replace it with your own route and add other routes as desired
router.get("/", (request, response) => {
response.json({"message": "app works!"});
});
app.use("/", router); // Load the router module
app.listen(8080, () => 'Server started and is listening on port: 8080');
I am building a Node application using Express, Massive JS, and Postgresql. I was using sequelize but decided to try Massive JS, so I started converting my code to use it.
I have a login endpoint that I'm trying to reach from my Angular 5 app and I am getting an error. This error only occurs on my deployed application. It does work locally without any issues.
Here is the specific error:
TypeError: Cannot read property 'get_user' of undefined<br> at login (/root/firstImpression/server/features/auth/authController.js:7:26)
Here is my folder structure:
+Server
-server.js
+config
-secrets.js
+db
-get_user.sql
+features
+auth
-authController.js
-authRoutes.js
server.js file contents:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
const cookieParser = require('cookie-parser');
const secrets = require('./config/secrets');
const massive = require('massive');
// used to create, sign, and verify tokens
var jwt = require('jsonwebtoken');
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
//routes
require('./features/auth/authRoutes')(app);
//Connect to database
massive(secrets.development).then(db => {
app.set('db', db);
});
// Angular DIST output folder
app.use(express.static(path.join(__dirname, '../dist')));
//Set up static files
app.use(express.static('../dist'));
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
get_user.sql file contents:
SELECT * FROM users WHERE username = $1;
authController.js file contents:
const jwt = require('jsonwebtoken');
const secrets = require('../../config/secrets');
const bcrypt = require('bcrypt');
module.exports = {
login: (req, res) => {
req.app.get('db').get_user(req.body.username).then(user => {
if(user[0]) {
bcrypt.compare(req.body.password, user[0].password,
function(err, result) {
if(result) {
var token = jwt.sign({user}, secrets.tokenSecret,
{expiresIn: '1h'});
res.status(200).json({
token: token,
user: user
})
} else {
res.status(200).json("Invalid username and/or
password.");
}
});
} else {
res.status(200).json("Could not find that user.");
}
})
}
}
authRoutes.js file contents:
var authController = require('./authController');
module.exports = (app) => {
app.post('/user-auth', authController.login);
}
The error is occuring in the authController.js file on this line:
req.app.get('db').get_user(req.body.username)
I've been reading the docs for massive js and learned the importance of keeping the DB folder on the same level where it's initialized, which is my server.js file.
As I stated earlier, when I run this on my local machine, it works great; However as soon as I deploy it to my live environment, I receive the error.
Any help or direction would be greatly appreciated. Let me know if any other information is required, and I will gladly provide it.
Your app setup should probably be wrap like
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
const cookieParser = require('cookie-parser');
const secrets = require('./config/secrets');
const massive = require('massive');
// used to create, sign, and verify tokens
var jwt = require('jsonwebtoken');
//Connect to database
massive(secrets.development).then(db => {
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
app.set('db', db);
// Angular DIST output folder
app.use(express.static(path.join(__dirname, '../dist')));
//routes
require('./features/auth/authRoutes')(app);
//Set up static files
app.use(express.static('../dist'));
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
});
I'm trying to load /users/(username) for specific user profile pages, however I'm getting a Cannot GET /users/test error. I had it working at one point but then I added a function and it's broken again (I'm thinking the problem may be there in the route). Here's the relevant files. Any help would be greatly appreciated. Thank you!
app.js:
const fs = require('fs');
const _ = require('lodash');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tipcup');
var db = mongoose.connection;
const routes = require('./routes/index');
const users = require('./routes/users');
const user = require('./routes/user');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// BodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport Init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator ({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/user/:username', user);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
user.js route:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
// GET user by username
router.get('/:username', function(req, res) {
//var username = req.params.username;
User.getUserByUsername(function(err, user) {
if(err) {
res.send('error');
next();
}
const vm = user;
res.render('user', vm);
});
//res.render('user');
});
module.exports = router;
Its looks like you are defining the User Id twice
In app.js you are mounting the users routes /user/:username with the line
app.use('/user/:username', user);
Then in user.js you are declaring the get to /:username with the line
router.get('/:username', function(req, res) {
I would think this would produce a route with the signature /user/:username/:username
I would suggest remove the /:username one of the files
router.get('/:username', function(req, res) {
var username = req.params.username;
User.getUserByUsername(username).then(function(err, user){
res.json(user);
});
for mongoose you can do this:
router.get('/:username', function(req, res) {
var username = req.params.username;
User.getUserByUsername(username,function(err, user){
res.json(user);
});
});