Cannot POST on JS and MongoDB - javascript

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.

Related

Can't handle post request

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)

First and Second input from a form give back 'null'

So basically I want to create a form that collects user's information and store it in database. Well the problem is that 'fname' and 'name'(the first 2 inputs from the form), for some reason, return 'null' even though they have been filled with text. The problem there is that I cannot add another user due to the fact that there is already a user with the given 'lname' and 'fname' -- in this case 'null'. The strangest part to me is that the other inputs seem to have no problem whatsoever. Any help/suggestion is appreciated.
My user.js Model:
var mongoose = require("mongoose");
var UserSchema = new mongoose.Schema({
firstName: {type: String, unique:true},
lastName: {type: String, unique:true},
email: {type: String, unique: true},
hasVoted: {type: Boolean, default: false}
});
module.exports = mongoose.model("User", UserSchema);
My form:
<!DOCTYPE html>
<html>
<head>
<title>POll</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="/stylesheets/landing.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript" async></script>
</head>
<body>
<div class="row">
<div style="width: 30%; margin: 25px auto;">
<form action="/" method="post">
<div class="form-group">
<input class="form-control" type="text" name="fname" placeholder="First Name">
</div>
<div class="form-group">
<input class="form-control" type="text" name="lname" placeholder="Last Name">
</div>
<div class="form-group">
<input class="form-control" type="text" name="email" placeholder="Email">
</div>
<div class="form-group">
<textarea class="form-control" name="comment">Comment(Optional)</textarea>
</div>
<div class="form-group">
<input type="submit" value="Submit">
</div>
</form>
</div>
</div>
My routes and create mongodb
var express = require("express");
var router = express.Router();
var User = require("../models/user");
router.get("/", function(req, res){
res.render("landing");
});
router.post("/", function(req, res){
// get data from form and add to campgrounds array
var fname = req.body.fname;
var lname = req.body.lname;
var email = req.body.email;
var comment = req.body.comment;
var newUser = {fname: fname, lname: lname, email: email, comment: comment};
// Create a new campground and save to DB
User.create(newUser, function(err, newlyCreated){
if(err){
console.log(err);
} else {
console.log(newlyCreated);
//redirect back to campgrounds page
res.redirect("/", {user: newlyCreated});
}
});
})
module.exports = router;
Shouldn't this:
var newUser = {fname: fname, lname: lname, email: email, comment: comment};
be this:
var newUser = {firstName: fname, lastName: lname, email: email, comment: comment};

i am not able to fetch data from html controls using get method in nodejs and mongodb

problem in code
var userID = req.userid;
var pwd = req.pwd;
console.log("userid = " + userID + "pass = " + pwd);
the console shows values undefined instead of input data
the console shows values undefined instead of input data
I want to take data from an html file and insert into the mongo database using get method. But I am not able to fetch data from the textbox.
Code in nodejs(index.js)
const express = require('express');
const path = require('path');
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const app = express();
app.use(bodyparser());
app.use(bodyparser.urlencoded({
extended: false
}));
app.use(bodyparser.json());
app.set('port', (process.env.PORT || 1000));
mongoose.connect('mongodb://localhost/TrackDB');
var Schema = new mongoose.Schema({
username: String
, pass: String
});
var users = mongoose.model('users', Schema);
app.get("/register", function (req, res) {
var userID = req.userid;
var pwd = req.pwd;
console.log("userid = " + userID + "pass = " + pwd);
new users({
username: userID
, pass: pwd
}).save(function (err, doc) {
if (err) {
res.json(err);
}
else res.send("Successfully Registerd!");
});
console.log("users = " + users);
});
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'));
});
app.listen(1000, () => {
console.log("Server Start......");
});
HTML Page (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LOGIN/REGISTER</title>
<style>
#container {
width: 40%;
margin: auto;
border: 1px solid;
padding: 10px;
padding-left: 200px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="container">
<h1>Register</h1>
<form action="/register">
<div id="register">
<input type="text" name="userid" id="txt_userid" placeholder="Enter user id">
<br>
<input type="password" name="pwd" id="txt_pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_register">Register</button>
</div>
</form>
<h1>Login</h1>
<form action="/login">
<br>
<br>
<div id="login">
<input type="text" name="user" id="userid" placeholder="Enter user id">
<br>
<br>
<input type="password" name="passw" id="pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_login">Login</button>
</div>
</form>
<h1 id="msg"></h1> </div>
</body>
</html>
Try this code
var userID =req.query.userid;
var pwd = req.query.pwd
You need to use POST request, and the data won;t be available in req object. Instead it will be available in req.body
Try:
var userID = req.body.userid;
var pwd = req.body.pwd;
console.log("userid = " + userID + "pass = " + pwd);
You have to use app.post method in node.js.
And use method = post.
<form action="/register" method="post">
<div id="register">
<input type="text" name="userid" id="txt_userid" placeholder="Enter user id">
<br>
<input type="password" name="pwd" id="txt_pass" placeholder="Enter password">
<br>
<br>
<button type="submit" id="btn_register">Register</button>
</div>
</form>
Sending data to node uses post, delete, put methods. But if you wish to fetch data back from node you can use .get() method.
I suggest try to print req(i.e console.log(req)). As might be data is stored in req.body.

How can I send data from client to server

I am new to nodejs.please help.
Here is my html and node.js code. I want to send email and password from login.html(client) to login.js(server) and validate from table storing email and password.
login.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/loginstyle.css" />
</head>
<body>
<form class="css" method="post" action="http://localhost:9383/valid" >
<fieldset >
<input type="text" name="email" class="inputemail" placeholder="Email" />
</fieldset>
<fieldset >
<input type="password" name="pass" class="inputpassword" placeholder="Password" />
</fieldset >
<fieldset >
<button type="submit" class="submit">Submit</button>
</fieldset>
</form>
</body>
</html>
login.js
var express = require('express')
, app = express()
, mysql = require("mysql");
app.get('/loginme', function (req, res) {
res.sendfile(__dirname + '/loginmysql.html');
});
app.post('/valid', function (req, res) {
console.log("hello");
var username=req.body.email;
var password=req.body.pass;
var connection = mysql.createConnection({
"hostname": "localhost",
"user": "root",
"password": "123",
"database": "login"
});
connection.connect();
connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){
if (err){
throw err;
}else{
for (var i in rows) {
console.log('name: ', rows[i].name);
name=rows[i].name;
res.redirect('/option');
}
}
});
connection.end();
});
You're missing a form parsing middleware. Try adding the body-parser middleware somewhere before your POST route.

getting values from a POST method in expressJS

I'm trying to register a user in my application. This is the HTML code:
<form id="registration_form" action="register" onsubmit="return validateForm();" method="post">
Username: <input type="text" id="username" name="user[name]" /><br />
Password: <input type="password" id="password" name="user[pass]" /><br />
Repeat Password: <input type="password" id="password_repeat" name="user[pass]" /><br />
Email: <input type="text" id="email" name="user[email]" /><br />
<button type="submit" value="Register">Register</button>
<div id="error_registration" style="color: red;">
</div>
</form>
What I do in the server is taking the values of name, pass and email.
var express = require('express')
, app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
)
, io = require('socket.io').listen(app)
, mongoose = require('mongoose')
, schemas = require('./schemas')
, Schema = mongoose.Schema;
app.listen(80);
app.configure(function(){
app.use(express.bodyParser());
});
[...]
app.post('/register', function (req, res) {
registerUser(req, function(result){
//do something
var username = req.body.username;
});
});
My question is: why username is always undefined? Am I reading it in the wrong way? How should I then?
Thanks
Your variable is user not username.
Look:
..input type="text" id="username" name="user[name]" ..
Also you can always do console.log(req.body) to see the POST vars in the terminal.

Categories

Resources