Cannot POST to app - javascript

A very simple page... server.js
var path = require("path");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.listen(8000, function() {
console.log("listening on port 8000");
})
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, "./static")));
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index');
})
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/basic_mongoose');
var QuoteSchema = new mongoose.Schema({
name: String,
quote: String
})
var Quote = mongoose.model('Quote', QuoteSchema);
app.post('/quotes', function(req, res) {
console.log("POST DATA", req.body);
var quote = new Quote({name: req.body.name, quote: req.body.quote});
quote.save(function(err) {
if(err) {
console.log('something went wrong');
} else {
console.log('successfully added a quote!');
res.redirect('/main');
}
})
})
index.ejs
<html>
<head>
<title></title>
</head>
<body>
<div id='container'>
<h2>Welcome to Quoting Dojo</h2>
<form action='/quotes' method='post'>
<p>Your Name: <input type = 'text' id ='name'/><p>
<p>Your Quote: <input type='text' id ='quote'/><p>
<button id='add' type='submit'>Add Quote</button>
</form>
<button id='skip'>Skip to </button>
</div>
</body>
</html>
I get "cannot /POST" when I click the submit button. Anyone?
Server loads, html page in chrome shows up. I fill in the boxes and click "add". I get the route http://localhost:8000/quotes and the error Cannot POST /quotes. Not sure what I did as I have action='post' to /quotes and app.post in the server. I don't know if I have any other issues. Thanks.

Use the name attribute instead of id, name is sent to the server, id is not.
HTML input - name vs. id

<form action='/quotes' method='post'>
<p>Your Name: <input name='name' type = 'text' id ='name'/><p>
<p>Your Quote: <input name='quote' type='text' id ='quote'/><p>
<button id='add' type='submit'>Add Quote</button>
</form>

Related

Javascript / EJS Code showing error : TypeError: Cannot read properties of null (reading 'name')

The code does run at first but the moment I submit my first post request, it gives the following error :
node:events:504
throw er; // Unhandled 'error' event
^
TypeError: Cannot read properties of null (reading 'name')
Currently using : Node.js, mongoose
Packages used : express, bodyParser, ejs, Mongoose
JS file code :
const express = require("express");
const app = express();
app.use(express.static("public"));
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
const ejs = require("ejs");
app.set("view engine", "ejs");
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/learndb");
const questionSchema =
{
question : String,
answer : String
};
const Question = mongoose.model("Question", questionSchema);
const subjectSchema =
{
name : String,
questions : [questionSchema]
};
const Subject = mongoose.model("Subject", subjectSchema);
app.post("/", function(req, res)
{
const subjectName= req.body.subjectName;
const subject = new Subject({ name: subjectName});
subject.save();
res.redirect("/");
});
app.get("/", function(req, res)
{
Subject.find({}, function(err, foundSubjects)
{
res.render("home", {whichSubjects: foundSubjects});
});
});
HTML/EJS File code:
<body>
<h1>Choose a Subject</h1>
<% whichSubjects.forEach(function(eachSubject) { %>
<div class="">
<form class="" action="/<%=eachSubject.name%>" method="get">
<button type="submit" name="button"> <%=eachSubject.name%></button>
</form>
</div>
<% }) %>
<div class="">
<form class="" action="/" method="post">
<input type="text" name="subjectName" value="">
<button type="submit" name="button">Add A Subject</button>
</form>
</div>
</body>
The answer was so simple but we missed it. The first thing wrong in your code are the paths. You have two paths named /. You want to make your home route the place your visualize all the data and then make a form that posts the data to a different route and upon success, should redirect to your home route. In your case all you have to do is change the post route on the hmtl to /addsubject and on the js file to app.post('/addsubject' rest of code
//Generate express app
const express = require('express');
const app = express();
app.set('views', './views');
app.set('view engine', 'ejs');
//Generate body parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Connect to MongoDB
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learndb');
const subJectSchema = new mongoose.Schema({
name: String,
questions: [{type: String}]
})
const Subject = mongoose.model('Subject', subJectSchema);
app.post('/addsubject', (req, res) => {
const subjectName = req.body.subjectName;
const subject = new Subject({ name: subjectName });
subject.save((err, subject) => {
if (err) {
console.log(err);
} else {
console.log("User Saved");
}
});
res.redirect('/');
});
app.get('/', (req, res) => {
Subject.find({}, (err, subjects) => {
if (err) {
console.log(err);
} else {
res.render('home', { subjectList: subjects });
}
});
});
app.listen(4000, () => {
console.log('Server started on port 3000');
});
<body>
<h1>Choose Subject</h1>
<div>
<form action="/addsubject" method="post">
<label for="name">Name</label>
<input type="text" name="subjectName" id="name">
<input type="submit" value="Create Subject">
</form>
</div>
<% if(subjectList.length> 0){ %>
<% subjectList.forEach(subject=>{ %>
<p>
<%= subject.name %>
</p>
<% }) %>
<% } else { %>
<p>No subjects found Add Some</p>
<% } %>
</body>

How to redirect to another page after serving a post request in Node.js?

I want to save the data submitted by the user through a form using post method and then redirect it to another html page that I have on my local machine, is there any way to achieve this using Node.js or express how do I do that?
Here is the html code for form:
<html>
<head></head>
<body>
<form action="post_register.html" method="POST">
university name:<input type="text" name="name" placeholder="University name"><br>
faculty Username:<input type="text" name="facul" placeholder="faculty username"><br>
password:<input type="password" name="password" placeholder="password"><br>
<button >register</button>
</form>
</body>
and here is the javascript file:
var express = require("express");
var app = express();
var bodyparser=require("body-parser");
app.use(bodyparser.urlencoded({ extended: true }));
app.listen(3000);
app.get("/domain_register",function(req,res)
{
res.sendFile(__dirname+"/domain_register.html");
})
app.post("/post_register",function(req,res)
{
console.log(req.body);
res.end("yes");
});
all I want is that after pressing submit button the data is received and the user is redirected to post_register.html file.
I tested below code in my computer and it worked. I added res.redirect('/success') line to the post request handler and created an handler for /success path:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
You can change /success path with your naming choice.
App.js
var express = require('express')
var app = express()
var bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({ extended: true }))
app.listen(3000)
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
app.get('/success', function (req, res) {
res.sendFile(__dirname + '/success.html')
})
app.post('/register', function (req, res) {
console.log(req.body)
res.redirect('/success')
})
index.html
<html>
<head></head>
<body>
<form method="post" action="/register">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
success.html
<html>
<head></head>
<body>
<h1>Welcome</h1>
</body>
</html>

how to pass user input from HTML form when using express.Router()

I have a file server.js that looks like so:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Bear = require('./models/bear');
mongoose.connect('mongodb://123:pass123#ds1383.mlab.com:53/bears');
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
var port = 8080;
var router = express.Router();
router.use(function(req, res, next){
//console.log("Working....");
next();
});
router.get('/', function (req, res){
res.json({ message: "API Works!"});
});
router.route('/bears')
.post(function(req, res) {
console.log("hi");
var bear = new Bear(req.body); // create a new instance of the Bear model
console.log(bear);
// save the bear and check for errors
bear.save(function(err) {
if (err)
return res.send(err);
res.json({ message: 'Bear created!' });
});
});
app.use("/", (req, res) =>{
res.sendFile(__dirname + "/index.html");
});
app.use('/books', router);
app.listen(port);
console.log("Listening on port "+ port);
And my Index.html file looks like so:
<head>
</head>
<body>
<form method="POST" action="/bears">
Enter Book to add
<input type="text" id="book_name"/>
<br /><br />
Enter Quantity
<input type="number" id="book_quantity"/>
<br /><br />
Enter Price
<input type="text" id="book_price"/>
<br /><br />
<button type="submit"> Add Book </button>
</form>
</body>
I was wondering why it doesn't enter the
router.route('/bears')
.post(function(req, res){});
when clicking the "Add Book" button even thought I've set the
action="/bears" attribute.
When testing with curl, it works fine, just not with this html form
I test with curl like so:
curl -i -X POST -H "Content-Type: application/json" -d '{ "book_name" : "Android", "book_quantity": 2,"book_price": 580 }' localhost:8080/books
I'm new to Javascript so any help would be appreciated!
For post call through html form, "name" attributes for all input tags are mandatory
<form method="POST" action="/books/bears">
Enter Book to add
<input type="text" id="book_name" name="book_name"/>
<br /><br />
Enter Quantity
<input type="number" id="book_quantity" name="book_quantity"/>
<br /><br />
Enter Price
<input type="text" id="book_price" name="book_price"/>
<br /><br />
<button type="submit"> Add Book </button>
</form>
Also use
app.use(bodyParser.urlencoded({ extended: true }));
in server code
This is because form sends post data in application/x-www-form-urlencoded format, so access as req.body.book_name in server.
if json format is needed then use javascript on client and make json and then send.
app.use("/", (req, res) =>{
res.sendFile(__dirname + "/index.html");
});
Is being used for all the requests and not just '/. Instead useapp.get()` to handle the index.html page. This should then let your requests go through.
app.get("/", (req, res) =>{
res.sendFile(__dirname + "/index.html");
});
And the endpoint would be /books/bears and not just /bears since your route use is app.use('/books',router) so your endpoints would need to start with /books
<form method="POST" action="/books/bears">

Save information to MongoDB database from form?

I want to save the information captured from an html form in a MongoDB database, I have the following code:
<!DOCTYPE html>
<html>
<head>
<title>Intro to Node and MongoDB</title>
</head>
<body>
<h1>Into to Node and MongoDB</h1>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
</html>
And the following javascript code would be my app.js
var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var mongoose = require("mongoose");
/*
mongoose.Promise = global.Promise;mongoose.connect("mongodb://localhost:27017/node-demo");
*/
var promise = mongoose.connect('mongodb://localhost:27017/node-demo', {
useMongoClient: true,
/* other options */
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Apparently the post request is working, filling in the fields and pressing the input type submit, however when checking the database is empty, just as it was when it was created. Does anyone know why I do not save the information?
I run your code here and the app.post was not called. It's because you're using app.use to send the index.html. app.use is used to bind middleware to your application. Instead, you should use app.get, which tells express to listen for requests to / and run the function when it sees one.
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});

reading html file input and sending to node.js for processing

I'm using node.js for a basic form-processing task.
The html file loads, but when I submit the form, it fails to process.
Here is the code I'm running right now:
formhandling2.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendfile('peanuts.html');
app.post('/myaction', function(req, res){
var userName = req.body.userName;
res.send ('Hello: ' + userName + '.<br>' + 'Try again.');
res.sendfile('peanuts.html');
});
app.listen(80);
peanuts.html
<html>
<head>
<title>Forms></title>
</head>
<body>
form action="/myaction" method="post">
<p>Enter your name:</p>
<input type="text" name="userName" placeholder="..." />
<br>
<button type="submit">Submit</button>
</body>
</html>
You have a syntax error in your server file
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendfile('peanuts.html');
})
app.post('/myaction', function(req, res){
var userName = req.body.userName;
res.send ('Hello: ' + userName + '.<br>' + 'Try again.');
res.sendfile('peanuts.html');
});
app.listen(80);
See above, after res.sendfile('peanuts.html') you have to close }) braces.
then you have html syntax error you have not started form tag. Correct code below
<html>
<head>
<title>Forms></title>
</head>
<body>
<form action="/myaction" method="post">
<p>Enter your name:</p>
<input type="text" name="userName" placeholder="..." />
<br>
<button type="submit">Submit</button>
</body>
</html>
everything else works nice i tested once fixed

Categories

Resources