How can I send data from client to server - javascript

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.

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)

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.

Html - Javascript: Mysql doesnt saving data in database

i just have a register button in my html as follows, which calls the register() function from the insert.js file. When i run alone the insert.js script it writes data to my database. The problem is that when i combine it(the js script) with this html code, it writes nothing. What im doing wrong?
<form method="post">
<div class="inputs">
<div class="input">
<input placeholder="Email" name="email" type="text">
<img src="img/mail.svg">
</div>
<div class="input">
<input placeholder="username" name="username" type="text">
<img src="img/user.svg">
</div>
<div class="input">
<input placeholder="password" name = "password" type="password">
<img src="img/pass.svg">
</div>
</div>
<button onclick="register()" >Register</button>
</form>
<script src="insert.js"></script>
my insert.js file
function register()
{
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "assessment"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO users (username, password) VALUES ('james', 'bond007')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
}
Well, it seems to me that js file its node which is back-end, installed on a server and the HTML it's front-end which runs on the user machine, that js it's fine but should be accessible for the HTML, the front, whoever uses your application, through an endpoint which you can do on node, but I could be wrong if you are using some kind of framework...

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 .

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.

Categories

Resources