NOT GETTING REDIRECT RESPONSE - node.js

In app.post("/compose"), I am trying to redirect the URL to the home page, but it's not redirecting to the homepage.
What mistake am I making?
Kindly help, redirecting to the homepage res.redirect("/") not working.
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const homeStartingContent = "HOME CONTENT ........";
const aboutContent = "ABOUT CONTENT .......";
const contactContent = "CONTACT CONTENT ......";
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
var posts = [];
app.get("/", function(req, res){
res.render("home", {homeContent: homeStartingContent});
console.log(posts);
});
app.get("/about", function(req, res){
res.render("about", {aboutContent: aboutContent});
});
app.get("/contact", function(req, res){
res.render("contact", {contactContent: contactContent});
});
app.get("/compose", function(req, res){
res.render("compose");
});
app.post("/compose", function(req, res){
const post = {
title: req.body.postTitle,
content: req.body.postBody
};
posts.push(post);
res.redirect("/");
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});

I was able to redirect when I ran your code in local by changing this:-
res.render("home", {homeContent: homeStartingContent});
to
res.send("I am in get method");
This means your code is working fine. The problem could be with your "home" page.
Could be an issue rendering it.
With your code, I was getting the following error:-
Failed to lookup view "home"
This was because there was no file named "home".
Is your code working fine in your system? If there is an error, please enter that in your question.

Actually it was a typing mistake from my side. Instead of passing action="/compose" method="post" into the form element, i mistakenly passed into the div element(like that div class="form-group" action="/compose" method="post").
<%- include('partials/header'); -%>
<h1>COMPOSE</h1>
<form class="form-group" action="/compose" method="post">
<div>
<label>Title</label>
<input type="text" class="form-control" name="postTitle">
</div>
<div class="form-group">
<label>Post</label>
<textarea class="form-control" rows="3" cols="25" name="postBody"></textarea>
</div>
<button class="btn btn-primary" type="submit" name="button">Publish</button>
</form>
<%- include('partials/footer'); -%>

Related

Body parser returning undefined for req.body request (SIMPLE LOGIN for beginner)

So I installed body parser via
npm i install express body-parser
and I wrote a simple code designed to input a user into an array after they complete a registration form.
but when I console.log the user it returns undefined for both email and password
here is the server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const PORT = 3000;
var Users = [{"email":"mike#gmail.com", "password":"456"}];
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/Register.ejs', (req, res) => {
res.render('Register.ejs')
})
app.post('/views/Register.ejs', (req, res) =>
{
const newUser = {
email: req.body.email,
password: req.body.password
};
Users.push(newUser);
res.json(req.body.email);
console.log(Users)
}
)
app.listen(PORT);
here is the html for the register page
<h1>Please Register</h1>
<body>
<form action="/views/Register.ejs" method="POST">
<div class="div">
<label for="email">Enter Email</label>
<input type="email" id="email"for="email" id="email" required>
</div>
<div class="div">
<label for="password">Enter new password</label>
<input type="password" for="password" id="password" required>
</div>
<button type="submit"> Register </button>
</form>
</body>
Only installing body-parser is not enough. You have to put them in the code as middleware.
Top of the code use:
var bodyParser = require('body-parser');
and then use the code in somewhere middle of the code:
app.use(bodyParser.json())

Can not get data from form in Node.js using express

I am building a small app that inputs movie name from the user and sends a request to an API that then sends the rating of that movie.
When I input the name of the movie in a form, that form submits to /movie-data (a get request) which I will eventually use to fire off an request to the API, but the problem is that I can not get the data that has been input by the user in the form.
Here is my app.js
const express = require("express");
const app = express();
const port = 4000 || process.env.PORT;
app.use(express.urlencoded({ extended: false }));
app.set("view engine", "ejs");
app.get("", (req, res) => {
res.render("index");
});
app.get("/movie-data", (req, res) => {
try {
const name = req.body.movieName; //undefined here
console.log(name);
res.redirect("/");
} catch (error) {
console.log(error);
res.sendStatus(500);
}
});
app.listen(port, () => {
console.log("Server running on port ${port}");
});
In the app.get("/movie-data".. request handler when i try to get the name of the movie it is undefined.
Here is my HTML form.
<div class="form-group">
<label for="name">Movie Name</label>
<input
type="text"
name="movieName"
required
class="form-control"
id="name"
/>
</div>
<button type="submit" class="btn btn-primary mt-4">Find</button>
</form>
According to my understanding a server could access a certain field of the form by the name defined in the input field like in the above HTML code I have defined name="movieName"

I'm stuck in rendering templates using express and handlebars

Please, explain me, why my code does not work?
I'm using express width handlebars, for form submit using Jquery Ajax. First render works properly, but second does not. I think that the problem is in nesting 'res.render'. Hope on your answers :-)
app.js
var express = require('express');
var app = express();
var template = require('consolidate');
var handlebars = require('handlebars');
var bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: false}));
app.engine('hbs', template.handlebars);
app.set('view engine', 'hbs');
app.set('views', __dirname);
app.get('/', function(req, res) {
res.render('index', {
myName: 'John'
});
});
app.post('/', function(req, res) {
var obj = {surname: req.body.surname, age: req.body.age};
res.render('Layout.hbs', obj, function(err, html) {
if(err) {
console.log(err);
} else {
console.log(html);
res.render('index.hbs', {
content: html
})
}
}
);
});
app.listen(8080, function() {
console.log('App listening on 8080');
});
index.hbs
<div class="wrapper">
<div class="container">
<p>{{myName}}</p>
</div>
<form action="" name="form" id="form" method="post">
<input id="surname" type="text" name="surname" placeholder="surname"><br/>
<input id="age" type="text" name="age" placeholder="age"><br/>
<input type="submit">
</form>
{{{content}}}
</div>
<script type="text/javascript">
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var surname = form.find('#surname').val();
var age = form.find('#age').val();
$.ajax({
type: 'POST',
data: {surname: surname, age: age},
success: function(res) {
console.log('Success');
},
error: function(err) {
console.log(err);
}
});
});
});
</script>
Layout.hbs
<div class="inner-container">
<h1>{{surname}}</h1>
<h2>{{age}}</h2>
<p>Render</p>
</div>
I think you are right, the problem is with nested res.render. When you call res.render, it renders a html and sends it to the client with a status code of 200.
You can call app.render on root level and res.render only inside a route/middleware. But keep in mind, res.render uses app.render internally to render template files. I don't think there is any need of rendering template separately.
Hope the answer helps you. It would be better for me to answer if I could see the error log that you are getting. If you provide that I would change my answer accordingly.
I think issue with binding delegation event with on() method..
$('form').on('submit', function(e) {
Replace it by
$(document).on('submit','form', function(e)){

why node.js bodyParser always returns 'undefined'?

In 'app.js' I have
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
'index.js' full codes
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function(req, res, next) {
res.render('index', { title: 'Here' });
});
router.post('/manager', function(req, res, next) {
var connection = mysql.createConnection({
host : 'localhost',
user : req.body.username,
password : req.body.password,
database : 'shops'
});
connection.connect(function(err){
if(!err)
res.render('manager', { title: 'Here' });
else
console.log("Error connecting database ...");
});
});
module.exports = router;
In 'index.html' login form
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' type='text'><br>
Password<br>
<input id='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>
In index.js line 12-13
req.body.username
req.body.password
Everytime I try to parse data from html form, they return 'undefined'. I'm new to node.js scripting. Am I doing something wrong?
You're missing name attributes on your <input> tags. Add them like:
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' name='username' type='text'><br>
Password<br>
<input id='password' name='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>

Not getting data in post form

i've been trying to get the data in a form with the POST method, but i don't get any, i've been reading a book to learn about expressjs.. this is my form:
<form method="post">
<div class="form-group">
<label for="usernameInput" class="col-md-2">Username</label>
<div class="col-md-12">
<input type="text" class="form-control" id="usernameInput" name="username" placeholder="Enter username">
</div>
</div>
<div class="form-group">
<label for="passwordInput" class="col-md-2">Password</label>
<div class="col-md-12">
<input type="password" class="form-control" id="passwordInput" name="password" placeholder="Enter password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Log in</button>
</form>
and this is my node code.
/*
Chat application for #node.js
express version.
*/
//Load modules.
var express = require('express'),
http = require('http'),
socket = require('socket.io'),
swig = require('swig'),
fs = require('fs');
//Load config.
console.log('Loading configuration.');
var config = fs.readFileSync('config.json');
var config = JSON.parse(config);
var port = config.port;
var views = config.views;
console.log('Configuration loaded.');
//Initiate express module in app.
var app = express();
//Global vars
var Title = "Node.js Chat";
var result = '';
app.engine('html', swig.renderFile);
//Set view engine.
app.set('view engine', 'html');
//Set the directory for views.
app.set('views', __dirname + '/views');
swig.setDefaults(
{
cache: false
});
app.get('/', function(request, response)
{
console.log('GET OK');
response.render('index',
{
'Title': Title,
'result': result,
});
});
app.post('/', function(request, response)
{
console.log('POST OK');
console.log(request.body);
response.render('index',
{
'Title': Title,
'result': 'Post detected.',
});
});
//logger.
app.use(function(request, response, next)
{
console.log('%s %s', request.method, request.url);
var file = request.url.slice(1 + request.url.indexOf('/'));
app.get(request.url, function(request, response)
{
response.render(file,
{
//Var to be named in the render : value;
'Title': Title,
'result': result,
});
});
next();
});
//Set directory for static files (css, js, img)
app.use(express.static(__dirname + '/public'));
//Run the app.
http.createServer(app).listen(port, function()
{
console.log('Server listening to ' + port);
});
i get "undefined" in request.body, which i dont know why i get this error, i've tried with other methods like request.param, or request.query, but they get nothing, i've made sure the post is detected and its why it sends the message that's being detected, but i want to get the data in the form..
You need the now-separate body-parser middleware. Run npm install body-parser or add body-parser to your package.json and npm install it.
Add var bodyParser = require('body-parser'); to your module-loading, then after instantiating your app, add the middleware with app.use(bodyParser());. That will populate req.body for the form.
add in app.js:
app.use(express.bodyParser());
As the comment indicated, it depends on the express version.
It works with 3.x as stated above.
For 4.0, you must manually include these frameworks that were previously included. See the note from vision media (overview tab):
https://github.com/visionmedia/express/wiki/Migrating-from-3.x-to-4.x
These are NOT included to allow independent updates

Resources