Can't handle post request - javascript

I'm trying to redirect using res.redirect() function. When I submit the form it should insert the data into the database and redirect me to home root. But the later is giving me this error:
Cannot POST /
this is my entire js file
const express =require("express");
const mongoose =require("mongoose");
const app=express();
const path=require("path")
const bodyparser= require("body-parser");
const Blog = require("./model/schema");
const { findById } = require("./model/schema");
app.use(express.static("public"));
app.set("views",path.join(__dirname+"/views"));
app.set("view engine","ejs");
app.use(bodyparser.urlencoded({extended:true}));
mongoose.connect("mongodb://127.0.0.1:27017/blogdb", {useNewUrlParser: true, useUnifiedTopology: true })
.then(()=>
{
console.log("Connection successful!");
})
.catch(err=>
{
console.log("Error: connection failed")
})
app.get("/",async(req,res)=>
{
const blogs=await Blog.find({});
//console.log(blogs);
res.render("blogdata/show",{blogs});
})
app.get("/create",async(req,res)=>
{
// const id=req.params["id"];
// const eblog= await Blog.findById(id);
res.render("blogdata/form");
})
app.post("/create",async(req,res)=>
{
await Blog.insertMany([
{name:req.body.author,blog:req.body.blogcontent}
])
res.redirect("back");
})
app.listen(3000,()=>
{
console.log("Server is up and running");
})
This is all the file I have
enter image description here
HTML form
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/formstyle.css">
<meta charset="utf-8" />
<title>create blog</title>
</head>
<body>
<div><h1><b>Create your own blog!</b></h1></div>
<div class="form">
<form action="/create" method="post">
<div class="name-in">
<label for="name">Author</label>
<br>
<input type="text" id="name" name="author" class="name" value="">
</div >
<div class="text-in">
<label for="para">Enter your blog</label>
<br>
<textarea name="blogcontent" id="para" cols="30" rows="10"></textarea>
</div>
<button type="submit" class="form" id="btn">Submit</button>
<!-- <label for="text">Edit your blog</label>
<input name="text" id="text"
type="text"
class="blog"
value= "" > -->
</form>
</div>
</body>
</html>
Please mention why this is happening and is there any better way to do this?

Well, you have an endpoint /create for the POST method, but the error says that you're trying to send the form to / on POST.
Make sure in your form that you add the correct url (meaning to add /create)

Related

How do I make Javascript (node.js) wait while I submit the form?

I would like the program/script to stop/wait after "console.log ('3')" until you click "Finished!" (and prior download of data from the above form).
Clicking this button would be equivalent to restarting the program / script from "console.log ('4')".
How can this be achieved?
code in app.js:
var express = require('express');
var http = require('http');
var path = require("path");
var helmet = require('helmet');
var rateLimit = require("express-rate-limit");
const port = process.env.PORT || 3000;
const { MongoClient, ServerApiVersion } = require('mongodb');
const { body, validationResult } = require('express-validator');
const { title } = require('process');
const app = express(),
{ engine } = require('express-handlebars'),
bodyParser = require('body-parser');
app.set('view engine', 'hbs');
app.use(express.static("public"));
app.use(express.json({ extended: false }));
//app.use(bodyParser({ extended: false }))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('handlebars', engine({
defaultLayout: 'main'
}))
app.set('view engine', 'handlebars')
async function readingFromForm() {
console.log('data download has started');
console.log('3');
app.post('/added', function(sReq, sRes) {
var newTitle = sReq.body.title;
console.log('title:', newTitle);
var newAuthor = sReq.body.author;
console.log('author:', newAuthor);
var newMood = sReq.body.mood;
console.log('mood:', newMood);
var newTime = sReq.body.time;
console.log('time:', newTime);
var newDate = sReq.body.date;
console.log('date:', newDate);
sRes.sendStatus(200);
console.log(sReq); //Caution! It generates a lot of "spam" in the console !!!
console.log(sRes); //Caution! It generates a lot of "spam" in the console !!!
});
console.log('4');
console.log('data has been downloaded');
}
async function main() {
const uri = "mongodb+srv://rafal:rafal#cluster0.gsf4h.mongodb.net/cattu?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
console.log('START');
console.log('1');
await client.connect(); // Connect to the MongoDB cluster
console.log('2');
await readingFromForm();
console.log('5');
await createListing(client, {
title: "newTitle",
author: "newAuthor",
mood: "newMood",
time: "newTime",
date: "newDate" // YYYY-MM-DD
})
console.log('END');
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
async function createListing(client, newListing) {
const result = await client.db("cattu").collection("test1").insertOne(newListing);
console.log(`New listing created with the following id: ${result.insertedId}`);
}
app.listen(port);
code in public/index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Cattu</title>
<link rel="stylesheet" href="styl.css">
<link rel="icon" type="image/x-icon" href="favicon.png">
</head>
<body>
<ul>
<li>Start</li>
<li>Formularz</li>
</ul>
<div id="poraDnia">
<div id="bgchange">
<div class="main">
<form method="POST" action="/added">
Podaj tytuł piosenki<br>
<input type="text" id="tytul" name="title" size="20px" required><br><br> Podaj wykonawcę<br>
<input type="text" id="wykonawca" name="author" size="20px" required><br><br> W jakim Jesteś nastroju?
<br>
<input type="checkbox" id="wesoly" value="wesoly" name="mood">
<label for="wesoly"> Wesoły/a </label><br>
<input type="checkbox" id="smutny" value="smutny" name="mood">
<label for="smutny"> Smutny/a </label><br>
<input type="checkbox" id="znudzony" value="znudzony" name="mood">
<label for="znudzony"> Znudzony/a </label><br>
<input type="checkbox" id="zmeczony" value="zmeczony" name="mood">
<label for="zmeczony"> Zmęczony/a </label><br>
<input type="checkbox" id="zdenerwowany" value="zdenerwowany" name="mood">
<label for="zdenerwowany"> Zdenerwowany/a </label><br>
<input type="checkbox" id="radosny" value="radosny" name="mood">
<label for="radosny"> Radosny/a </label><br>
<input type="checkbox" id="neutralny" value="neutralny" name="mood">
<label for="neutralny"> Neutralny/a </label><br>
<br>
<label for="pora"> Podaj porę dnia </label><br>
<select name="time" id="pora" required>
<option value="rano">Rano</option>
<option value="poludnie">Południe</option>
<option value="wieczor">Wieczór</option>
<option value="noc">Noc</option>
<option value="nie_pam">Nie pamiętam</option>
</select><br><br>
<label for="pora"> Podaj datę </label><br>
<input name="date" type="date"><br><br>
<button type="submit" class="submit">Skończone!</button>
<button type="reset" class="submit">Resetuj!</button>
</form>
</div>
<div class="content">
<div id="tlo3" onmouseover="rotatemoon(this)" onmouseout="rotatemoonB(this)">
<div id="obiekt_glowny3" onmouseover="movein(this)" onmouseout="moveout(this)">
<div id="ksiezyc_srodek"></div>
</div>
</div>
<div id="tloGwiazdy1">
<div id="gwiazda1"></div>
<div id="gwiazda2"></div>
<div id="gwiazda3"></div>
</div>
<div id="tloGwiazdy2">
<div id="gwiazda11"></div>
<div id="gwiazda12"></div>
<div id="gwiazda13"></div>
</div>
<div id="tlo2">
<div id="obiekt_glowny2" onmouseover="bigSun(this)" onmouseout="smolSun(this)">
<div id="promien1"></div>
<div id="promien2"></div>
<div id="promien3"></div>
<div id="promien4"></div>
<div id="promien5"></div>
<div id="promien6"></div>
<div id="promien7"></div>
<div id="promien8"></div>
<div id="promien9"></div>
<div id="promien0"></div>
</div>
</div>
<div id="tlo1">
<div id="obiekt_glowny1">
<div id="slonce" onmouseover="blouClounds(this)" onmouseout="whiteClounds(this)">
<div id="promien11"></div>
<div id="promien12"></div>
<div id="promien13"></div>
<div id="promien14"></div>
</div>
</div>
<div id="chmura1"></div>
<div id="chmura2"></div>
</div>
</div>
<div class="info1">
<br><br><br><br><br><br><br><br><br>Zobacz pełną historię
</div>
<div class="info2">
<!-- Tutaj chcemy pobierać dane z bazy żeby móc je wyświetlić (pobierać może zewnętrzny skrypt) -->
*Dane pobrane z bazy*
</div>
</div>
</div>
<script src="script1.js"></script>
</body>
</html>
I think you need to understand client-server communication, server should be ready to handle request whenever client made,
You may update your readingFromForm function to call createListing like
async function readingFromForm(client) {
console.log('data download has started');
console.log('3');
app.post('/added', async function(sReq, sRes) {
var bodyData = sReq.body;
await createListing(client, bodyData);
sRes.sendStatus(200);
// sReq is an request object contains all request related information(data, objects & functions)
// sRes is an response object contains all response related information(data, objects & functions)
});
console.log('4');
console.log('data has been downloaded');
}
and in the main function, you need to pass client object to readingFromForm function like
// await readingFromForm();
await readingFromForm(client);
use on click event handler in form. It will only submit the form when submit event will occur.
use onsubmit in form tag and an event handler in js.

Cannot POST on JS and MongoDB

I'm very new to web development, and now I'm trying to build a login page which uses HTML, CSS and Javascript for the website, and MongoDB database to store the data received from the user. I followed a few tutorials on YouTube, but for some reasons the data cannot be posted.
Here are the codes that I have so far:
(Javascript)
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded( {extended: true}));
mongoose.connect("mongodb+srv://cs196:cs196#userdata.sn7wv.mongodb.net/cs196", { userNewUrlParser: true}, {useUnifiedTopology: true} );
// create a data schema
const notesSchemaCreate = {
username: String,
email: String,
password: String,
confirm_password: String
}
const Note = mongoose.model("NoteCreate", notesSchemaCreate)
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
})
app.post("/", function(req, res) {
let newNote = new Note({
username: req.body.username,
email: req.body.email,
password: req.body.password,
confirm_password: req.body.confirm_password
});
newNote.save();
})
app.listen(3000, function() {
console.log("server is running on 3000")
})
(And here are the HTML codes)
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<title>Login Site</title>
<link rel="stylesheet" href="./main.css">
</head>
<body>
<div class="container">
<!-- Create an account -->
<form class="form form--hidden" id="createAccount" method= "post" action="/">
<h1 class="form__title">Create Account</h1>
<div class="form__message form__message--error"></div>
<div class="form__input-group">
<input type="text" id="signupUsername" class="form__input" name="username" autofocus placeholder="Username">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="text" class="form__input" name= "email" autofocus placeholder="Email Address">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="password" class="form__input" name= "password" autofocus placeholder="Password">
<div class="form__input-error-message"></div>
</div>
<div class="form__input-group">
<input type="password" class="form__input" name= "confirm_password" autofocus placeholder="Confirm Password">
<div class="form__input-error-message"></div>
</div>
<button class="form__button" type="submit">Continue</button>
<p class="form__text">
<a class="form__link" href="./" id="linkLogin">Already have an account? Sign In</a>
</p>
</form>
</div>
</body>
I'm trying out the results using localhost:3000, which looks like this:
The result simply gave me cannot POST / in a new page.
Please let me know if there might be something off with my MongoDB setting, or if you want to see how the setting is right now, since I don't know what parts to show you guys and I don't want to make this post incredibly long.
Thanks in advance for anyone who can help me out with this! And I apologize in advance if my codes or this post is formatted horribly.
Each endpoint function must end the request-response cycle by sending a response ( res.send(), res.json(), res.end(), etc).
model.create() is asyncronous. Mark your function as async
So the solution would be:
app.post("/", async(req, res) => {
try {
const newUser = await Note.create({
username: req.body.username,
email: req.body.email,
password: req.body.password,
confirm_password: req.body.confirm_password
});
res.json({status: "success", message: "user created successfully", user: newUser})
} catch(error) {
res.json({status: "fail", message: error.message ? error.message : "could not create user"})
}
})
P.S: never expose your secret(mongo_uri, stripe_key, etc.) keys public.

Node.js express: trying to get text from HTML form, req.body empty

I'm trying to build a basic text to speech form, but I cannot grab the text from the form.
I'm trying to get text from an HTML form using an express server and req.body turns up empty every time. I've tried using body-parser and changing the enctype on the form, nothing seems to work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>index.html</title>
</head>
<body>
<h1>Speech!!</h1>
<main>
<form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
<div id="text-container">
<label for="text-box">Text to Speech!</label>
<input type="text" id="text-box" title="text" placeholder="Type what you want to say here!"/>
</div>
<div class="button-container">
<button type="submit" id="submit-button">Speak!</button>
</div>
<div class="button-container">
<button type="reset" id="clear-form">Clear Text</button>
</div>
</form>
</main>
</body>
</html>
app.js
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const configRoutes = require("./routes");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
configRoutes(app);
app.listen(3000, () => {
console.log("Speech Server");
});
index.js
const express = require("express");
const speakRoutes = require("./speak");
const constructorMethod = (app) => {
app.use("/speak",speakRoutes);
app.use("*", (req,res) => {
res.sendFile("index.html", { root: "./public" });
});
};
module.exports = constructorMethod;
speak.js
const express = require("express");
const router = express.Router();
router.post("/", async (req,res) => {
console.log("POST");
console.log(req.body);
res.sendFile("index.html", { root: "./public" });
});
module.exports = router;
I would greatly appreciate some help! Thank you!
Your input has no name, give your input a name so you know what property to look for in the form:
<input type="text" id="text-box" name="whatever" ... />
EDIT: A client-only example. One field has a name.
$('form').on('submit', function(e) {
e.preventDefault();
console.log($(e.currentTarget).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Speech!!</h1>
<main>
<form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
<div id="text-container">
<label for="text-box">Text to Speech!</label>
<input type="text" id="text-box" title="text" placeholder="Type what you want to say here!" name="whatever" />
<input type="text" id="text-box" title="text" placeholder="I have no name so I won't be sent!" />
</div>
<div class="button-container">
<button type="submit" id="submit-button">Speak!</button>
</div>
<div class="button-container">
<button type="reset" id="clear-form">Clear Text</button>
</div>
</form>
</main>
I fixed my own issue! It worked by changing post to get in the route and the html form method, and req.body to req.query

Hey I don't know where to start when inserting data into MySql from html form using node.js

I just want to know where to start with getting my html page to work with my back end code and database. I want to insert information into my table with a basic html login page but all i found were confusing sources, maybe i suck at googling but was wondering if someone can help telling me where i should start and what else i need to learn in order to achieve this,
The code below is what i managed to learn and implement.
var http = require('http');
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var url = require('url');
var pages = require('html-pages');
const css = fs.readFileSync(`${__dirname}/public/art.css`, 'utf-8');
const htmlLogin = fs.readFileSync(`${__dirname}/login.html`, 'utf-8');
const htmlSignUp = fs.readFileSync(`${__dirname}/signup.html`, 'utf-8');
//static files for login
app.use('/login', express.static('./public'));
//
app.get('/login', function(req,res,next) {
res.writeHead(200, {'Content-Type' :'text/html'});
res.write(htmlLogin);
next();
}).listen(3000);
app.get("/signup", function(req,res, next) {
res.writeHead(200, {'Content-Type':'text/html'});
res.write(htmlSignUp);
});
and here is my html page
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<link href="./signup.js">
</head>
<body>
<div class="signupBox">
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</div>
</body>
</html>
Learning how to back end with node.js and mysql just got stuck in knowing how to do this task,
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var sql = require('mysql');
var fs = require('fs');
var url = require('url');
var myDB = sql.createConnection({
//properties...
host: 'localhost',
user: 'root',
password: '',
database: 'sampleDB'
});
myDB.connect(function(err) {
if (err) {
console.log('There is an error');
} else {
console.log("Connected to Database");
}
});
As what I am seeing from your code, you already setup login and signup page, it it's working than now you now to save signup data you can create new route like
app.post("/register", function(req,res, next) {
console.log('request data', req.body) // you will get signup for data here.
});
and in signup for you need to add action like -
<form method="post" action="localhost:3000/register">
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</form>
you can do same with login verification, send login detail as in below route -
app.post("/checkLogin", function(req,res, next) {
console.log('request data', req.body) // you will get login detail here.
});
Hop this help.
Update html:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<link href="./signup.js">
</head>
<body>
<div class="signupBox">
<h1 id="signUp">Sign Up!</h1>
<form action="signup" method="POST">
<!-- it's important to define name="xx" here otherwise you'll get 'undefined' value in server side -->
<div> <input type="text" placeholder="First Name" name="firstname"> </div>
<div> <input type="text" placeholder="Last Name" name="lastname"> </div>
<div> <input type="text" placeholder="Email" name="email"> </div>
<div> <input type="password" placeholder="Password" name="password"> </div>
<input id="submit" type="button" name="" value="Sign Up">
</form>
</div>
</body>
</html>
Add this code in server side:
app.post ("/signup", function(req, res) {
// get info from form
var firstname = request.body.firstname;
var lastname = request.body.lastname;
var email = request.body.email;
var password = request.body.password;
var adduserquery = "INSERT INTO `myTable` (`firstname`,`lastname`,`email`,`password`) VALUES ('" + firstname + "', '" + lastname + "', '" + email + "', '" + password + "')";
if (email) {
// check if e-mail already exists
myDB.query('SELECT * FROM `myTable` WHERE email = ?', [email], function(error, results, fields) {
if (results.length > 0) {
response.send('This e-mail is already registered!' );
} else {
// execute query to insert data
myDB.query(adduserquery, (err, result) => {
if (err) {
return response.status(500).send(err);
}
// if insert is successful, return you to homepage
response.redirect('/home');
});
}
});
}
}
}
Thats great you have already added the express module , i woud suggest try adding form tag and give the action to the form tag , on which you want to hit eg /signup and change your input type button to submit this will workout .
<div class="signupBox">
<form action='/signup'>
<h1 id="signUp">Sign Up!</h1>
<div>
<input text="text" placeholder="First Name" name="" value="">
</div>
<div>
<input text=text" placeholder="Last Name" name="Last Name" value="">
</div>
<div>
<input text="text" placeholder="Email" name="Email" value="">
</div>
<div>
<input text="text" placeholder="Password" name="Password" value="">
</div>
<input id="submit" type="button" name="" value="Sign In">
</form>
</div>
Now if you click on submit the data can be getable inside the /signup route you have created using the req.body.NAME_VALE , once you got the value you can insert it into the database .

TypeError: Cannot read property 'xxx' of undefined jQuery

I am trying to send a post request from site to server which includes user input data. I am getting TypeError: Cannot read property 'vehicle' of undefined as a response here.
HTML and script data:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Car Finder</title>
<link rel="stylesheet" href="style.css">
<center><h1>Craigslist Vehicle Finder</h1></center>
</head>
<body>
<form class="form">
<input type="text" name="vehicle" value="" id="vehicle">
<label for="vehicle">Vehicle</label>
</form>
<form class="form">
<input type="text" name="miles" value="" id="miles">
<label for="miles">Miles</label>
</form>
<label class="container">
<input type="checkbox" id="checkbox">
<span class="checkmark"></span>
<label for="checkbox">Manual</label>
</label>
<select id="select" class="City">
<option value="null">Select Location</option>
</select>
</div>
<form class="submit Search">
<input type="submit" value="Search Craigslist"><br/>
</form>
<script>
var select = document.getElementById("select"),
arr = ["atlanta","austin","boston","chicago","dallas","denver","detroit","houston","lasvegas","losangeles","miami","minneapolis","newyork","newhaven","orangecounty","philadelphia","phoenix","portland","raleigh","sacramento","san diego","seattle","sfbay","washingtondc"];
for(var i = 0; i < arr.length; i++) {
var option = document.createElement ("OPTION"),
txt = document.createTextNode(arr[i]);
option.appendChild(txt);
select.insertBefore(option, select.lastChild);
}
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$.post('http://localhost:3000', { vehicle: 'input#vehicle', miles: 'input#miles', location: 'select' }, function (err, result) {
if (err) {
console.log(err);
} else {
return data;
}
});
</script>
</body>
</html>
Server side method to receive the POST data:
app.post('/', (req, res, err) => {
if (req.method == 'POST') {
console.log(req.body.vehicle)
console.log(req.body.miles)
console.log(req.body.location)
}
})
using express server btw
There is an npm module called body-parser that extracts form data and sends that data to the req.body object. Using this module, you will be able to access form elements by name, in this case req.body.vehicle in your route handlers which should solve the issue. May be worth checking out the documentation:
https://www.npmjs.com/package/body-parser
EDIT: So I gave this a try using body-parser and got req.body printing out form contents in route handler. Hope this helps :)
app.js (Express code)
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname));
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/', function(req, res) {
res.sendFile('index.html');
});
app.post('/findvehicle', urlencodedParser, function (req, res, err) {
console.log(req.body.vehicle);
console.log(req.body.miles);
console.log(req.body.location);
res.redirect('index.html');
});
app.listen("2000");
index.html
<form class="form" method="post" action="/findvehicle" >
<input type="text" name="vehicle" value="" id="vehicle">
<label for="vehicle">Vehicle</label>
<input type="text" name="miles" value="" id="miles">
<label for="miles">Miles</label>
<input type="checkbox" name="location" id="option1" value="Atlanta" autocomplete="off" checked=""> Atlanta
<input type="checkbox" name="location" id="option2" value="Austin" autocomplete="off"> Austin
<label for="miles">Location</label>
<input type="submit" value="Search Craigslist"><br/>
</form>

Categories

Resources