I have recently started using node.js and while using body parser I stumbled upon an error which i have no clue about.
I get an error cannot read property 'date' of undefined although i am mentioning date in my html part.
my codes are as follows:
app.js:
var moment = require('moment');
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
app.set('view engine','ejs');
app.get('/',function(req,res){
res.render('index');
})
app.get('/ans', function(req,res){
res.render('ans');
})
app.post('/', function(req,res){
var date = req.body.date;
console.log(date);
res.render('ans',{"date": date});
});
app.listen(3000,function(err){
if(err) console.log(err);
else
console.log("App is running");
});
index.ejs:
<!DOCTYPE html>
<html>
<head>
<title>timestamp</title>
</head>
<body>
<h1>API Basejump: Timestamp microservice</h1>
<h2>Enter the date</h2>
<form action="/" method="post" >
<input type="text" name="date">
<input type="submit">
</form>
</body>
</html>
ans.ejs:
<!DOCTYPE html>
<html>
<head>
<title>timestamp</title>
</head>
<body>
<h1>API Basejump: Timestamp microservice</h1>
<p>Date: <% date %></p>
</body>
</html>
You need to setup express to use body-parser
var app = express();
app.use(bodyParser.urlencoded({ extended: false }))
Related
I am building an app in node.js ran into a problem because I couldn't get an HTMLElement
Is it possible to do something like
document.querySelector("#div")
Or
document.getElememtById("div")
But in Node.js express?
My code:
Index.js:
const express = require('express');
// App set up
const app = express();
app.get('/', (req, res) => {
res.sendFile("Public/index.html", {root: __dirname});
})
app.use(express.static('Public'));
// Listen
app.listen(3000, () => console.log('started'));
/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="div"> Hello world! </div>
</body>
</html>
So I am working on this calculator app using Express.js and when I use the res.send Method I am not receiving any kind of response now.
I expect my webpage to send me the sum as in the calculator.js file.
I am using nodemon as well.
This is HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form method="POST">
<input name='num1' placeholder='num1' type='text'>
<input name='num2' placeholder='num2' type='text'>
<button
type="submit" name="submit">Calculate</button></form>
<h1 class='answer'></h1>
</body>
</html>
This is calculator.js
const express = require('express');
const app = express();
const port = 3000;
const bodyParser = require("body-parser");
const {
json,
urlencoded
} = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html")
});;
app.post("/", function (req, res) {
console.log(req.body);
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var sum = num1 + num2;
res.send(sum);
});
app.listen(port, () => console.log(`Example app listening on port port!`))
you can't use res.send() to send number, it will be sent as a http status code. You can simply convert calculated sum to string and then send it:
res.send(sum.toString())
res.send has been deprecated in the latest version of Express (4.17.1).
Using res.sendStatus instead solved my problem.
This is probably a simple solution, however I cannot figure out how to carry my JSON object over to my view. Normally you'd throw JSON into res.render() inside your app.get .. unfortunately I am having trouble. A problem arises because i need to be able to send form data from html to my API request, then grab that JSON object and display it in my view. I can see it in my console, but unable to carry it over to html. Would love some help or guidance on how to improve my code or find a solution. Any help is appreciated! - View code below:
Server.js
var path = require('path');
var express = require('express');
var exphbs = require('express-handlebars');
var bodyParser = require('body-parser');
var Bls2 = require('bls2');
var app = express();
app.engine('html', exphbs({ extname: '.html' }));
app.set('view engine', 'html');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var blsRequest = function(req, res, inputContent){
const API_KEY = //bls API key here
let bls = new Bls2(API_KEY);
console.log('this is seriesID =', inputContent);
let options = {
'seriesid': [inputContent],
'startyear': '2008',
'endyear': '2018',
// ...
};
bls.fetch(options).then(function (response) {
var data = JSON.stringify(response)
console.log(data);
console.log('API Call Complete')
res.send({data : data}); //need to render home view and JSON HERE
});
}
app.get('/', function (req, res) {
res.render('home');
});
app.post('/', function(req, res){
let inputContent = req.body.seriesID;
blsRequest(req, res, inputContent);
});
app.listen(8000);
html
<!DOCTYPE html>
<html>
<head>
<title>LBS</title>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="crossorigin="anonymous"></script>
</head>
<body>
<div class="container-fluid">
<form id="seriesID">
<div class="form-group" method="post" action='/'>
<label for="seriesID">Input Series ID</label>
<input type="text" class="form-control" name="seriesID" placeholder="Series ID">
</div>
<button class="btn btn-primary" type="submit" >Search</button>
</form><br>
uhh JSON should be here: {{data}}
</div>
</body>
<script type="text/javascript">
$("#seriesID").submit(function (event) {
$.post('/', $("#seriesID").serialize(), function (data) {
//data is the response from the backend
});
event.preventDefault();
});
</script>
</html>
use res.render('home',{data});
because your{{data}} is undefined that's why it is not printing anything
it is even better to use {{JSON.stringify(data)}}
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.
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});
});