Processing posted data in Express + Node.js? - javascript

I am attempting to capture the information that is being sent from a form in Express and Node.js. Here are the relevant contents of my app.js and index.hjs:
app.js
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
index.hjs
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>{{ title }}</h1>
<p>Welcome to {{ title }}</p>
<form method="post" action="/">
<input type="test" name="field1">
<input type="test" name="field2">
<input type="submit">
</form>
</body>
</html>
When attempting to submit the form on http://expressserver.domain:3000, I receive a 404 error. Does anyone have any ideas on what the issue is and point me in the right direction?

Instead of using app.use, have a real POST route.
app.post("/", function(req, res) {
console.log(req.body);
res.json(req.body);
});
You need an actual route for it to kick in, and you want .post, not .use, because the latter is for all possible HTTP verbs, which means it'll try to access req.body for things that never have one (GET, OPTIONS, HEAD, etc) and crash your script.

I've found a really good example here: http://runnable.com/U0sU598vXio2uD-1/example-reading-form-input-with-express-4-0-and-body-parser-for-node-js which works.

Related

HTTP header 'X-Frame-Options' and 'frame-ancestors' directive do not block clickjacking. In Angular-Express js application

I have an application with a front-end in Angular served by an S3 bucket, and a server in Express js.
To avoid clickjacking I am trying to take all possible actions so: "frame-buster" techniques for the client side and anti-clickjacking header for the server.
For the latter I have tried all the solutions indicated online. That is, I set the "X-Frame-Options" to "DENY" as I do not need any iframes in my application and set the "frame-ancestors" directive with the following code:
const app = express();
const helmet = require("helmet");
app.use(helmet.frameguard({ action: "DENY" }));
app.use(
helmet.contentSecurityPolicy({
directives: {
frameSrc: ["none"],
frameAncestors: ["none"],
},
})
);
I then used this html file to test my application:
<!DOCTYPE html>
<html>
<head>
<title>Iframe test</title>
</head>
<body>
<input type="text" id="inputSite" style="width:400px"/>
<input type="button" value="Open"
onclick="document.getElementById('iframe').src=document.getElementById('inputSite').value"
/>
<br/>
<iframe id="iframe" style="width:100%; height:800px;" ></iframe>
</body>
</html>
And these are the first http requests sent by the app:
[1]: https://i.stack.imgur.com/kaAOJ.png
[2]: https://i.stack.imgur.com/I12Rj.png
[3]: https://i.stack.imgur.com/p6HTQ.png
Does anyone know what this behaviour is due to and how I can solve it?
Thank you very much, have a nice day

Sitemap xml in node for google console

Im trying to add a sitemap at Google Search Console.
I have this code:
Route
router.get("/sitemap", function(req, res){
res.render("sitemap.ejs");
});
Sitemap.ejs
<html>
<head>
<title>Sitemap</title>
<link rel="alternate" type="application/rss+xml" title="" href="sitemap.xml" />
</head>
<body>
</body>
</html>
But when i try to add the sitemap to google it says that the sitemap cant be in html format.
How can i make it valid to Google Search Console?
Solution
var path = require("path");
router.get('/sitemap.xml', function(req, res) {
res.sendFile(path.join(__dirname, 'path', 'sitemap.xml'));
});

href link between two webpages on server in node.js with express package and EJS template engine

I have a server_render.js as follows. I have used express package of NPM. I have tow webpages in views directory, one is home.ejs and the other is portal.ejs. I used the EJS template engine.
var express=require('express')
var app=express()
const port=process.env.PORT || 10002
//app.use(express.static(__dirname+'/public'))
//template engine
app.set('view engine','ejs');
//homepage
app.get('/',function(req,res){
res.render('home.ejs');
})
//signin page: 127.0.0.1:10002/signin
app.get('/signin',function(req,res){
res.render('portal.ejs');
});
//run nodejs loop server
app.listen(port,function(err){
if(err){
throw err
}
console.log('server is listening on '+port+' ...')
})
views/home.ejs looks like this:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Portal</title>
</head>
<body>
<div>You need to <a href='portal.ejs'>sign-in</a></div>
</body>
</html>
and views/portal.ejs is this:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Portal</title>
</head>
<body>
<input name="username" id="username" type="text" placeholder="username"></input>
<input name="password" id="password" type="text" placeholder="password"></input>
</body>
</html>
I want to create a link from home.ejs to portal.ejs. I tried href="portal.ejs" however it did'nt work. I wonder what's the method.
You can't link to the actual ejs files. In your code you have declared the following paths:
//homepage
app.get('/',function(req,res){
res.render('home.ejs');
})
//signin page: 127.0.0.1:10002/signin
app.get('/signin',function(req,res){
res.render('portal.ejs');
});
This means that your express app has urls at '/' and '/signin'. On each of those two paths you have declared to render either home.ejs or portal.ejs as the output HTML.
Just point the links to '/' and '/signin' instead of the actual template files.

Node Server Not Loading CSS File

I'm making a chat application using a node server but when I start the node server and point my browser to localhost:3000 it loads the HTML document but not the CSS file which is supposed to load when the HTML document loads. How do you load the CSS file so that the HTML document uses it?
HTML document code
<html>
<head>
<title>Socket.IO Chat by Flow</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="chat.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="css.css">
<body>
<table align="center" id="chat-box">
<td>
<ul id="messages"></ul>
<form action="">
<input type="text" placeholder="Press enter to send a message..." autocomplete="off" id="m">
</form>
</td>
</table>
</body>
JavaScript document code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', function(socket){
});
http.listen(port, function(){
console.log('Listening on port: ' + port);
});
You haven't defined any routes that would provide the CSS file. The only route you've defined is
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});
...which will only ever serve chat.html.
To serve other files/resources, define other routes, perhaps a catch-all route that serves any matching file from a public directory.
For instance, this tutorial says you can serve any static files from the directory public by doing this:
app.use(express.static('public'));
More about routing in the routing tutorial. That whole series of tutorials may well be useful, in fact.

angular express infinite loop

I have no idea why but my express/angular app is causing an infinite loop when loading the index page... I have my app setup:
app.configure(function() {
// set up our express application
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.bodyParser()); // get information from html forms
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.methodOverride());
});
And my Angular app route provider:
var app = angular.module('myApp', ['ngRoute', 'angularFileUpload', 'rcWizard', 'rcForm', 'rcDisabledBootstrap', 'ui.bootstrap']).
config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/login", { templateUrl: "/partials/login.ejs", controller: "LoginCtrl" })
.otherwise({ redirectTo: "/login" });
}
]);
My index.ejs file holding all the includes:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<link rel="stylesheet" href="css/style.css"/>
<link rel="stylesheet" href="css/form-styles/rcWizard.css"/>
<link rel="stylesheet" href="css/bootstrap-formhelpers.min.css"/>
</head>
<body>
<div ng-view></div>
<script src="bower_components/ng-file-upload/angular-file-upload-shim.min.js"></script>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script src="bower_components/ng-file-upload/angular-file-upload.min.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="javascripts/lib/helpers/sel_options.js"></script>
<script src="javascripts/lib/helpers/xml2json.js"></script>
<script src="javascripts/lib/helpers/form-lib/jquery.bootstrap.wizard.js"></script>
<script src="javascripts/lib/helpers/bootstrap-formhelpers.min.js"></script>
<script src="javascripts/lib/helpers/form-src/directives/rcSubmit.js"></script>
<script src="javascripts/lib/helpers/form-src/modules/rcForm.js"></script>
<script src="javascripts/lib/helpers/form-src/modules/rcDisabled.js"></script>
<script src="javascripts/lib/helpers/form-src/modules/rcWizard.js"></script>
<script src="javascripts/app.js"></script>
<script src="javascripts/services.js"></script>
<script src="javascripts/filters.js"></script>
<script src="javascripts/directives.js"></script>
<script src="javascripts/controllers/LoginCtrl.js"></script>
</body>
</html>
And finally express:
app.get('/', function(req, res){
res.render('index');
});
app.get('/partials/login.ejs', function (req, res) {
res.render('/partials/login.ejs', { 'message': 'test 111' });
});
app.get('*', function(req, res){
res.render('index');
});
This seems really straightforward, but for some reason the server just continuously loads all the script files over and over again that are defined in my index.ejs file. All the examples I've seen set it up exactly this way... and I have tried multiple variations of paths, settings, etc. Does anything standout?
EDIT
here is my login.ejs partial:
<% include navbar_public.ejs %>
<div class="container" ng-controller="LoginCtrl">
<script>var message="<%-message%>";</script>
<div class="col-sm-6 col-sm-offset-3">
<h1 class="form-fonts"><span class="fa fa-sign-in"></span> Login</h1>
<!-- show any messages that come back with authentication -->
<div ng-if="message.length > 0" class="alert alert-danger">{{message}}</div>
<!-- LOGIN FORM -->
<form action="/login" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="shimmy-button btn btn-success btn-lg">Login</button>
</form>
<hr>
<p>Need an account? Signup</p>
<p>Or go home.</p>
</div>
</div>
Four things to explore:
You didn't include a copy of /partials/login.ejs so it's possible there's something in there that's causing the problem.
You are asking Angular's router to load /login when anything but /login is requested. This type of route setup can sometimes create infinite loops - try a different 'otherwise' as a test to help narrow down the issue.
For any request except these two URLs, you are rendering your index page. That means if the request comes in even slightly odd, it's going to dump out index all over again. Now, your index page has all those script and JS tags... Which leads me to:
You're using relative paths on many/most of your CSS/JS resources. You do not have a BASE HREF meta tag... That means when your browser is on /login, it's going to try to request these things as /login/css/style.css and so on. That shouldn't happen because this is only meant to be a partial at this point, but if any of the above items (or anything else) is going wrong, this is going to snowball.
I strongly recommend using your browser's Network panel and/or a debugging tool like Charles Proxy to review the exact sequence of requests your browser is issuing. That will almost certainly clue you in to the final issue.
If you're still having trouble and plan to reply back, please include the template for the login.ejs partial, and comments about unusual network requests. Please also talk more about how you know / why you say your app is infinite-looping and exactly where you suspect this is happening (server, client, both, etc.)

Categories

Resources