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"
Related
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())
I have form post job.html and a button post. I want that when someone submits this form the values save in database and then i get these values on another helper's feed.html page. Right now, my values are saving in database but i am unable to understand how to get those values in next page.
This is the part of html code for helpers feed.
<div class="col-md-10" >
<div> Description:
<input type="text" id="desc" name="budget"class="form-control">
<div>
<div> Category:
<input type="text" id="category" name="budget" class="form-control">
</div>
<div > City:
<input type="text" id="city" name="budget" class="form-control">
</div>
<div > Budget
<input type="text" id="budget" name="budget" class="form-control">
</div>
This is node.js file. post.js
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'sahoolat1',
database : 'fyp_sahoolat'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
var app = express();
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/job post.html'));
});
app.post('/post',(request,response,next)=>{
var description=request.body.description;
var contact_number=request.body.contact_number;
var city=request.body.city;
var budget=request.body.budget;
var category=request.body.optradio;
var query=connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)",[null,description,category,city,contact_number,budget],function(err){
if(err)
console.log(err);
else
console.log("moving");
});
next();
});
app.get('/post',(request, response) => {
connection.query("SELECT * FROM jobs",(err, result) => {
if(err) {
console.log(err);
}
else {
console.log(result);
res.send(result);
}
});
});
app.listen(3000);
The code runs fine till the line where i am saving in database and it prints "moving" on console.
I want to get each field value in the respective text fiels(as shown in screenshot)
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'); -%>
I'm trying to build a basic registration page using node.js, express, mongoDB and AngularJS.
Before I tried to implement this registration functionality, I was using Angular routing for my views.
See the contents of my app.routes file below...
angular.module('app.routes', [])
.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "views/Login.html"
})
.when("/Register", {
templateUrl: "views/Register.html"
})
.when("/Home", {
templateUrl: "views/Home.html",
controller: "homeController"
})
.when("/CocktailDetails", {
templateUrl: "views/CocktailDetails.html",
controller: "cocktailDetailsController"
})
.when("/Favourites", {
templateUrl: "views/Favourites.html",
controller: "favouritesController"
})
.otherwise({
redirectTo: "/"
})
})
When the app loads it will direct the user to a login page, if they don't have an account there's a link to go the register page, url for this page is http://localhost:3000/#!/Register.
Please see view for the Register page below...
<div class="main">
<p class="sign" align="center">Register</p>
<form class="form1" action="/Register" method="POST">
<input class="un " type="email" align="center" placeholder="Email" name="username" required>
<input class="pass" type="password" align="center" placeholder="Password" name="password" required>
<a class="submit" align="center">Register</a>
</div>
So when they click the submit link/button it will perform a POST request, to create a new user in the userDB.
Please see server.js file content below...
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const router = express.Router();
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(express.static('node_modules'));
app.use(express.static('public'));
mongoose.connect("mongodb://localhost:27017/userDB", { useNewUrlParser: true });
const userSchema = {
email: String,
password: String
};
const User = new mongoose.model("User", userSchema);
//Routes
app.get("/", function (req, res) {
res.render("Login");
});
app.get("/Register", function (req, res) {
res.render("Register");
});
app.get("/Home", function (req, res) {
res.render("Home");
});
app.get("/CocktailDetails", function (req, res) {
res.render("CocktailDetails");
});
app.get("/Favourites", function (req, res) {
res.render("Favourites");
});
app.use(router);
const port = 3000;
app.listen(port);
console.log('Server is running on port 3000');
//POSTS
app.post("/Register", function (req, res) {
const newUser = new User({
email: req.body.username,
password: req.body.password
});
newUser.save(function (err) {
if (err) {
console.log(err);
} else {
res.render("Home")
}
});
})
I've mirrored my angular routes for the express routes.
But when I click the register button, nothing happens, checking the console, no errors but no POST request is made.
What am I missing here? I've tried changing the gets in the server.js but no luck.
I'm wondering if it's got something to do with the fact angular is putting #! on the url for each view.
Do I need to set HTML5 mode to true in my angular route file?
My file structure for the views is public > views.
For now I'm just trying to get a basic username and password into the database, I will look at implementing passport and encryption at a later stage.
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