using express csurf with ajax doesnt work - node.js

i am new with node js. i try to use csurf token with express using AJAX. here is my code
from server (app.js)
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
app.set('view engine', 'ejs')
app.set('views', 'views')
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.use(express.static(__dirname + '/public'));
app.get('/form', csrfProtection, function (req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', parseForm, csrfProtection, function (req, res) {
console.log(req.body.name); // <--- it is doesnt show in my terminal
res.send('data is being processed')
})
app.listen(3000);
HTML (send.ejs)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="<%=csrfToken%>">
<title>Document</title>
</head>
<body>
<form>
<input type="text" name="name" value="Jhon Doe" class="inp-name">
<input type="submit" value="Send" class="btn-send">
</form>
<script src="/javascripts/script.js"></script>
</body>
</html>
JS file (script.js)
document.querySelector('.btn-send').addEventListener('click',
() => {
const name = document.querySelector('.inp-name').value;
// Read the CSRF token from the <meta> tag
const token = document.querySelector('meta[name="csrf-
token"]').getAttribute('content')
// Make a request using the Fetch API
fetch('/process', {
credentials: 'same-origin', // <-- includes cookies in the request
headers: {
'CSRF-Token': token // <-- is the csrf token as a header
},
method: 'POST',
body: {
name: name
}
})
});
when i try to run this i think it doesnt work because when i see in my terminal the name of Jhon Doe doesnt appears.
i try this example from this site http://expressjs.com/en/resources/middleware/csurf.html

Related

app.set('view engine','ejs'); ^ TypeError: app.set is not a function

Problem in the template engine in express validation
I m expecting to resolve my problem
app.js
const express=require('express')
const app= express;
const port = 5000;
//set template engine
app.set('view engine','ejs')
//navigation
app.get('',(req,res)=>{
res.render('index')
})
app.get('/resgiter',(req,res)=>{
res.render('resgiter')
})
app.listen(port,() =>
console.info(`App listening on port:${port}`)
)
error in the template engine
You missed to invoke express in second line of Your code:
Instead of:
const app = express;
You should provide:
const app = express();
and forward slash / in this snippet:
app.get("/", (req, res) => {
res.render("index");
});
app.js
const express = require("express");
const app = express();
const port = 5000;
//set template engine
app.set("view engine", "ejs");
//navigation
app.get("/", (req, res) => {
res.render("index");
});
app.get("/resgiter", (req, res) => {
res.render("resgiter");
});
app.listen(port, () => console.info(`App listening on port:${port}`));
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>ejs it's Awesome! ;-)</h1>
</body>
</html>
folder&file structure and console output:
browser output:

Node.js/Express post route failing

Trying out Node.js for the first time. My POST route is failing with "Cannot POST /admin/add-product.html". GET request is being served fine from the same route. I have had a look around here. Several answers to similar issues but nothing is helping. Here is my code:
./index.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const adminRoutes = require('./src/routes/admin');
const shopRoutes = require('./src/routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.listen(3000);`
./src/routes/admin.js
const path = require('path');
const express = require('express');
const router = express.Router();
// served on /admin/add-product GET route
router.get('/add-product', (req, res, next) => {
res.sendFile(path.join(__dirname, '../', 'views', 'add-product.html'));
});
// served on /admin/add-product POST route
router.post('/add-product', (req, res, next) => {
console.log(req.body);
res.redirect('/');
// res.send('<h1>product saved</h1>');
});
module.exports = router;
./src/views/add-product.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Add Product</title>
</head>
<body>
<header>
<nav>
<ul>
<li>Shop</li>
<li>Add Product</li>
</ul>
</nav>
</header>
<main>
<form action="/admin/add-product.html" method="POST">
<input type="text" name="title" /><button type="submit">
Add Product
</button>
</form>
</main>
</body>
</html>
Thank you!!!
The action in the form need to match the route declare in the NodeJS application, it should be :
<form action="/admin/add-product" method="POST">
Remove the .HTML from the action attribute of the form.

Why does my styles get rejected when i change route inside my express nodejs app?

This is my index.js file
const express = require('express')
const bodyParser = require('body-parser')
const getRouter = require('./routes/getRoute')
const path = require('path');
const expressHbs = require('express-handlebars');
const app = express();
app.engine('hbs', expressHbs({
defaultLayout: false
}));
app.set('view engine', 'hbs');
// app.set('views', 'views');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/get',getRouter.router);
app.listen(3000, ()=>{
console.log('server has started on port: 3000')
})
And this is my getRouter.js file
const express = require('express')
const router = express.Router();
const path = require('path');
const data = require('./data');
let message = `It's Working`;
router.get('/', (req,res,next)=>{
res.render(path.join(__dirname, '..', 'views/index'), {msg: data.data.codename});
});
exports.router = router;
exports.message = message;
And finally, this is my index.hbs file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<h1>{{msg}}</h1>
</body>
</html>
Now whenever i change the route from / to basically anything like /codename inside getRouter.js , the styles inside index.hbs gets turned off somehow and only pain html is rendered.
Can someone help me figure this out as which part of the code is causing this? Thank you

EJS does not render value returned from res.render

I'm getting the page redirects correctly however when I'm going to list this result in the front-end the value is not shown just the command of the EJS in my front-end view.
I've tried to pass the output value in several different ways but none worked...
This my root files.
My index.js
var http = require('http');
var express = require('express'),
mongoose = require('mongoose'),
ejs = require('ejs'),
nunjucks = require('nunjucks'),
path = require('path'),
mysql = require('mysql'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
logger = require('morgan');
var errorHandler = require('errorhandler');
app.use(logger('dev'));
app.use(bodyParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
import config from "./config/config";
import mongodb from "./config/mongodb";
import passport from "./config/passport";
import * as setup from "./middleware/setup";
import app from "./config/express";
import routes from "./routes";
import User from './models/User';
export function start() {
return new Promise((resolve, reject) => {
mongodb().then((db) => {
let server = http.createServer(app);
// save references
app.db = db;
app.server = server;
app.config = config;
// init passport
passport(app);
// register setup check middleware
app.use(setup.check);
// setup routes
routes(app);
// start server
app.server.listen(config.server.port, (err) => {
if (err) {
return reject(err);
}
resolve(app);
});
}, reject);
});
};
app.set('views', __dirname + '/templates');
app.engine('html', require('ejs').renderFile);
var api = express.Router();
app.use('/', api);
api.get('/test-ejs', function (req, res) {
res.render('test.html', { title: 'Return sucess!' });
});
api.get("/templates",function(req, res){
var path = __dirname + '/templates/';
res.sendFile(path + "index.html");
});
My HTML template test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test EJS</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- styles -->
<link href="stylesheets/style.css" rel="stylesheet">
</head>
<body>
<%= title %>
</body>
</html>
Thank for helping me! xD
You are using .html file for rendering the data but in your app.js you have defined it as .ejs under app.engine line.
So either you have change the .html file type to .ejs or you have to replace your app.engine line with this
app.set('view engine', 'html');

Ejs rendered vars are undefined

I'm writing my first webb ap with nodejs and express, using ejs templates.
now when I'm rendering the html files it all works fine, but when I try to render the files with parameters, it seems like the rendered ejs template can't find the parameters I've sent to it.
here is my file structure :
project/
Views/
index.ejs
login.ejs
public/
all the css files ..
node_modules/
server.js
and here is my server.js :
var express = require('express');
var app = express();
const cookieParser = require('cookie-parser');
const session = require('express-session');
const bodyParser = require('body-parser')
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/Public'));
app.use(cookieParser());
app.use(session({secret: '1234567890QWERTY',resave: false, saveUninitialized: false})); // change the secret to safer one
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function(req, res) {
if (req.session.user == undefined) {
// if user is not logged-in redirect back to login page //
res.render('login');
} else {
console.log(req.session.user);
res.render('index', {username:req.session.user});
}
});
app.get('/login', function(req, res) {
res.render('login');
});
app.listen(8080);
console.log('port: 8080');
and here is my index.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Dashboard</title>
</head>
<body>
<div><%= username %></div>
</body>
</html>
and for some reason whenever I try to access index.ejs, it returnes an error -
"username is not defined"
any idea what I'm doing wrong? the examples online looks exactly the same
thanks !
after Fadi Bitar answered this is how my server get event looks like and it's stil won't work:
app.get('/', function(req, res) {
if (req.session.user == undefined) {
// if user is not logged-in redirect back to login page //
res.render('login',{username:req.session.user});
} else {
console.log(req.session.user);
res.render('index', {username:req.session.user});
}
});
// about page
app.get('/login', function(req, res) {
res.render('login',{username:req.session.user});
});
In the initial code, it should work... Without seeing it my guess is that you are trying to echo <%=username%> in login.ejs.
Your updated code has a couple of points where you're using a variable that doesn't exist.
if (req.session.user == undefined) {
res.render('login',{username:req.session.user});
}
Here you're saying 'if req.session.user is undefined, set username to req.session.user' (undefined).
Then this bit does the same..
app.get('/login', function(req, res) {
res.render('login',{username:req.session.user});
});
I assume here that when you go to /login req.session.user is not set, so that's why that errors...
I believe you are missing the "username" variable in your get function.
Make sure you do:
res.render('/', {username: "example username"});

Resources