How to parse POST response body in Node - javascript

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.get(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
console.log(req.body.crypto);
});
app.listen(3000, function(){
console.log("server is running in port 3000");
});
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.get(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
console.log(req.body.crypto);
});
app.listen(3000, function(){
console.log("server is running in port 3000");
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Bitcoin ticker</title>
</head>
<body>
<h1>Bitcoin Ticker</h1>
<form action="/" method="post">
<select name="crypto">
<option value="BTC">Bitcoin</option>
<option value="ETC">Ethereum</option>
<option value="LTC">Litecoins</option>
</select>
<select name="fiat">
<option value="USD">US Doller</option>
<option value="GBP">GB Pounds</option>
<option value="EUR">EU Euroes</option>
</select>
<button type="submit" name="button">Check</button>
</form>
</body>
</html>
have an issue in javascript code when iam requesting for post request the browser says Cannot read property 'crypto' of undefined
when iam running the code there is no error but when iam selecting cannot read
property "crypto"
and i think the errror might be in here
console.log(req.body.crypto);

Your req.body is undefined,
you have to make this line
app.get(bodyParser.urlencoded({extended: true}));
to
app.use(bodyParser.urlencoded({extended: true}));

Looks like your req.body is undefined.
Guess the problem is with the body-parser.
Try changing this line
app.get(bodyParser.urlencoded({extended: true}))
To
app.use(bodyParser.urlencoded({extended: true}))
Instead of applying body-parser with app.get, do it with app.use

Subburaj and Ron537 are both correct because body-parser is a middleware and in express you use the method use to include a middleware to your express program. in your case to include the body-parser module/middleware in your app, do app.use(bodyParser.urlencoded({extended: true})) if you want to be posting both sub-document and app.use(bodyParser.urlencoded({extended: false})) if you dont want to be posting sub document

Related

body-parser doesn't work and req.body returns empty

I have an ejs template with a simple form with just a value:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cambia email</title>
</head>
<body>
<form action="/user/cambia-email" method="POST">
<input type="text" name"email" id="email">
<input type="submit" value="Modifica email">
</form>
</body>
</html>
In my app.js I tried to call a console.log(req.body) but it returns empty "{}".
This is my app.js code:
const fs = require("fs");
const express = require("express");
const jwt = require("jsonwebtoken");
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const { verifyToken, signToken, deleteToken } = require("./middleware/user-auth");
require("dotenv").config();
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.get("/user/cambia-email", verifyToken, (req, res) => {
res.render("cambia-email");
});
app.post("/user/cambia-email", verifyToken, (req, res) => {
console.log(req.headers);
console.log(req.body);
res.send("Hai richiesto la modifica dell'email. Sei autorizzato!");
});
app.get("/login", signToken, (req, res) => {
res.send();
});
app.get("/logout", deleteToken, (req, res) => {
res.send("Logout effettuato")
});
app.get("/user/profile", verifyToken, (req, res) => {
const tema = req.user.tema;
res.render("profile", { tema });
});
app.get("/user/message", verifyToken, (req, res) => {
res.send("Sei autorizzato!");
});
app.listen(3000, () => console.log("Server in ascolto sulla porta 3000..."));
In other questions a lot of people said to use app.use(bodyParser.urlencoded({ extended: false })); but nothing change.
I tried .json() too but nothing seems change. By the way I tried console.log(req.headers) too and it returns: origin: 'http://localhost:3000',
'content-type': 'application/x-www-form-urlencoded' so urlencoded should work but it doesn't.
Any solution? Thanks
Ok guys I solved my own problem. I post my solution for anyone who need:
basically I rewrote my form in my ejs file so:
<form action="/user/cambia-email" method="post">
<label form="email">Email:</label>
<input type="text" name="email" id="email"><br><br>
<input type="submit" value="Modifica email">
</form>
The problem was that the name doesn't have an equal after (name"email" instead of name="email").
The way I used to parse the body is:
app.use(bodyParser.urlencoded({ extended: false }));
I suggest to set extended to true to avoid any warning but only the value of body.

NodeJS no response on submit

I have a local server running and an input form for users. I want when they press submit simply to output a message "Thank you!". Instead when pressing submit, nothing happens and after some time I get the message that the server dropped the connection. Could somebody help me please?
NodeJS:
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname +'/images'));
app.get('/', function(req, res){
res.sendfile('main.html');
});
//app.listen(port, function(){
// console.log('server is running on ' + port);
//});
app.post('/submit', function(req, res){
console.log(req.body.rank);
});
HTML:
<form method="POST" action="/submit" >
<img src="images/Picture1.png" style="width:280px;"/>
<br />
<select name="rank" size="1" style="width:80px;" required>
<option value="" selected disabled hidden>Rank</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<br />
<input type="submit" value="Submit" name="submit" id="submit"/>
</form>
Your post handler does nothing
app.post('/submit', function(req, res){
console.log(req.body.rank);
});
You can do the following action,
Redirect on another route with res.redirect :
app.post('/submit', function(req, res){
console.log(req.body.rank);
// redirect on /
return res.redirect("/");
});
Render a success html file:
app.post('/submit', function(req, res){
console.log(req.body.rank);
// render success
return res.sendfile('success.html');
});
Return json :
app.post('/submit', function(req, res){
console.log(req.body.rank);
// render success
return res.status(200).json({message: "OK"})
});
Its happed because you in your post handler never produces any feedback to client, just log to console rank. Try something like
app.post('/submit', function(req, res){
console.log(req.body.rank);
res.json(req.body.rank);
});

ng-include is not working with node.js server

I have create a simple page using angular.js and node.js server, ng-include is not working.
console error: 404 (not found)
index.html
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="">
<div ng-include="'views/header.htm'"></div>
<h1>heading one</h1>
</div>
</body>
</html>
header.htm
<h1>heading one</h1>
server.js
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(__dirname + '/' + 'index.html');
console.log("----------------");
});
app.listen(3000);
OutPut
heading one
404 indicate the file is not existing. make sure the HTML file exist in given path. Also, there is a typo error. should be views/header.html
<div ng-include="'views/header.html'"></div>
I am not sure if it is the right way but it works. Add another get method for the html file which is to be included.
index.html
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="">
<div ng-include="'/header'" method="GET"></div>
<h1>heading one</h1>
</div>
</body>
</html>
server.js
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(__dirname + '/' + 'index.html');
console.log("----------------");
});
app.get('/header', function(req, res){
res.sendFile(__dirname + '/' + 'header.html');
console.log("----------------");
});
app.listen(3000);
If any suggestions/corrections/better methods, I would like to know please.

Node js : Using Handlebars and Bodyparser together

In this basic program I would like to get user input using 'body parser' and then enter that input via handlebars onto the index page. I have attempted many times but can't seem to acheive it. Also does handlebars and bodyparser go together or should I be using something different.
Template:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<header>
<h1>Bodyparser and Handlebars</h1>
</header>
<form method="post" action="/">
<input type="text" name="name1">
<input type="submit" value="Submit">
</form>
{{test}}
</body>
</html>
Node.js
var express = require('express');
var app = express();
var handlebars = require('express-handlebars');
var path = require("path");
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('view engine', 'html');
app.engine('html', handlebars({
defaultLayout: 'base',
extname: '.html'
}));
app.use(express.static(path.join(__dirname, 'public'))); //public directory
app.get('/index', function(req, res) {
res.sendFile('index.html', { root: __dirname });
});
app.get('/', function (req, res) {
res.render('index', {
test: req.body.name1});
});
app.post('/', function(req, res){
console.log(req.body.name1);
});
app.listen(3000);
Your post to / should be:
app.post('/', function(req, res){
res.render('index', {
test: req.body.name1});
});
And you are done.
Body-parser and handlebars work perfect togheter. Body-parser allows you to collect the request data inside the router controller and handlebars is a template engine that render the variables and more stuff.
You need to pass the text that you want to display to the POST router controller.
<form action="/" method="post">
name1: <input type="text" name="name1"><br>
<input type="submit" value="Submit">
</form>
Put that form in other view or anywhere you want
Inside the controller pass the request parameter to handlebars:
app.post('/', function(req, res){
res.render('index', {
test: req.body.name1});
});

node.js variables will not be parsed

i am new in node.js and express.
in my test app the html variables will not be parsed.
what is the problem?
server.js
enter var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(express.static(__dirname));
app.get('/', function(req, res) {
res.render('index', {
wert : 'hallo'
});
});
app.post('/', function(req, res) {
var wert = req.body.wert;
var html = 'Hallo: '+wert+'!\n'
+ 'Mach\'s nochmal!';
res.send(html);
});
app.listen(8882);
console.log('Server port: 8882');
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Startseite</title>
</head>
<body>
<p>Hallo <%= wert %>, dies ist mein kleiner Webserver!</p>
<br>
<form action="/" method="post">
<input type="text" width="40" name="wert" value="<%= wert %>">
<input type="submit" value="submit">
</form>
</body>
</html>
the value parameter <%= wert %> in the view is not parsed.
why? how to do it?
thank you
jet
Express doesn't come with a view-engine by default. You need to add one, in your case EJS.
Using the command line, type:
npm install ejs
server.js now becomes:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(express.static(__dirname));
app.get('/', function(req, res) {
res.render('index', {
wert: 'hallo'
});
});
app.post('/', function(req, res) {
var wert = req.body.wert;
res.render('index', {
wert: wert
});
});
app.listen(8882);
thank you ben,
your ejs configuration was good.
I had to install express, ejs, body-parser. that was ok.
then i had to remove the line with app.use(express.static(__dirname));
and i had to change
app.set('views', __dirname + '/views');
to
app.set('views', __dirname);
for my original path.
then everything was ok!
greez
jet

Categories