I'm trying to send an AJAX POST request for a login page using javascript via Node.js however I don't really know how to do it. Sorry that I'm really new to this. Here's my code:
In HTML:
<form>
<label for="email"><b>Email Address</b></label><br>
<input type="text" name="email"><br>
<label for="password"><b>Password</b></label><br>
<input type="text" name="password"><br><br>
<input type="submit" class = "button" value="Login" onclick= "submitlogin()">
</form>
In JS:
function submitlogin(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState ==4 && this.status == 200){
console.log("success");
} else if (this.readyState == 4 && this.status == 401) {
console.log("Failed");
}
};
xhttp.open("POST","/login",true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(JSON.stringify({ email: this.email, password: this.password }));
}
Route:
var user = [{
EmailAddress: 'anne#gmail.com',
Password: 'first'
}]
router.post('/login', function(req, res, next) {
if((req.body.email === user[0].EmailAddress) && user[0].Password === req.body.password){
res.status(200).send();
} else {
res.status(401).send();
}
});
What should go into xhttp.send()? What am I doing wrongly? Can anyone help me with this? (preferably just javascript not jQuery) Thank you!
This is a typical issue about how to deal with the info passed to server using a way that you didn't expected.
There's a lot of things to improve in your code, but i won't focus on this right now. So, first of all, if you pay attention to what happens in your browser right after the submit button is clicked, on the URL you can see the typed inputs in querystring format. And it isn't referencing the /login route descripted.
Something like:
http://localhost:3000/?email=marcelobraga%40hotmail.com&password=agoodpassword
It happened because the Form element, by default, uses the parameters to communicate with your server. Not the object "Body" that you're expecting to receive through the HTTP Request object.
If you really want to access the login data passed as URL parameters, you will need just to fix your code in your front and backend to pass correctly object and prepare your server to read it on the right place.
I strongly advise you not to use the form html element this way. Either use the XMLHttpRequest. I suggest to use the Axios to do deal with the HTTP requests and send Body informations to avoid explicit such a sensitive information like logins could be. Other reason to use Axios is for easy syntax and clean code.
See how i made it with axios:
In HTML (I will insert all the HTML to you see the importation the Axios Lib tag):
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!-- importing axios to this document -->
<title>Document</title>
</head>
<body>
<label for="email"><b>Email Address</b></label><br>
<input type="text" id="email" name="email"><br>
<label for="password"><b>Password</b></label><br>
<input type="text" id="password" name="password"><br><br>
<input type="submit" class="button" value="Login" onclick="submitlogin()">
</body>
</html>
In JS file:
const emailInput = document.getElementById("email").value //getting the value from input typed
const passwordInput = document.getElementById("password").value //getting the value from input typed
axios.post('/login',
{
email: emailInput,
password: passwordInput
}
)};
In expressjs:
const express = require("express")
const app = express();
const path = require('path');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.post('/login', (req, res) => {
console.log(req.body); //console to verify the body data received on this endpoint request
const user = [{
EmailAddress: 'anne#gmail.com',
Password: 'first'
}];
if((req.body.email === user[0].EmailAddress) && user[0].Password === req.body.password){
res.status(200).send("Success");
console.log("Success");
} else {
res.status(401).send("Wrong email or password");
console.log("Wrong email or password");
}
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Conclusion
The way that you was doing this made the data unreachable on the backend. The backend was expecting to receive the information to proceed with the verifications on the Body data of the Request. And you was passing it as a query parameter.
You can pass information using params or query params to the backend, but the login information must be more protected. Sending it in your body avoid people to find this data lookin in your history, for example. It's not the most secure way, because someone can catch this data on the middle. But, anyway, is something you should know.
I hope i could help you.
Related
I am trying to make a basic login system using Express, where if the user's username and password are correct according to a MySQL database, it adds a short "Success!" or "Failure" message to the bottom of the page when it receives a POST request.
I've tried using res.write("<p>Success!</p>") and res.send("<p>Success!</p>"), but neither have worked - instead they just create a new page with "Success!".
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form id="contact-form" method="POST" action="/login">
<label for="Username">Username: </label>
<input name="Username" maxlength="45"><br><br>
<label for="Password">Password: </label>
<input name="Password" type="password" maxlength="45"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
JS:
const port = 3000;
const express = require("express");
const mysql = require("mysql2");
const app = express();
const bodyParser = require("body-parser");
var conn = mysql.createConnection({
host: "localhost",
database: "database",
user: "<Username>",
password: "<Password>"
});
conn.connect((err) => {
if(err) throw err;
console.log("Connected to database.");
})
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({
extended: false
}));
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/Login.html");
});
app.post("/login", (req,res) => {
let form = req.body;
let sqlQuery = "SELECT * FROM logins WHERE Username = '" + form.Username + "' AND Password = '" + form.Password + "';";
conn.query(sqlQuery, (err, result, fields) => {
if(err) throw err;
if(result.length == 1) {
res.write("<p>Success!</p>")
} else {
res.write("<p>Failure.</p>")
}
})
});
app.listen(port);
So, how could I append a short p element / text to the bottom of an HTML file?
Okay,
So when the submit button in the login form is hit, it creates a totally new request and the old page is no longer in the context of request.
So, res.write() creates a new page, since a new request is generated.
If you want to append the failure and success messages on the same page, you can use ajax request instead of default form submission.
Send the ajax request, you will receive the response without a page reload, and then upon receiving the response, using javascript, you can append a new element with message from the server
const contactForm = document.getElementById('contact-form');
contactForm.addEventListener('submit',(e)=>{
e.preventDefault();
const username = contactForm.elements['username'].value;
const password = contactForm.elements['password'].value;
// now make the ajax call, you can use any library like FetchAPI, axios or even jQuery Ajax
fetch('http://backend/endpoint',{
method: 'POST',
body: JSON.stringify({username,password})
})
.then((res)=>{
return res.json();
})
.then((data)=>{
console.log(data)
// you can append new element here
// based on data (success or failure)
})
})
I want to build a login page for my web app and I want to send data to my express server using fetch but when I log the req to the console the "req.body" is an empty object even if I sent an object with name and password properties can anyone help
client_side code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="text" id="name" name="name" />
<input type="password" id="password" name="password" />
<button onclick="send()">login</button>
<script>
async function send() {
let name = document.getElementById('name').value
let password =
document.getElementById('password').value
let res = await
fetch('http://localhost:3000/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name,
password
})
})
if(res.redirected) {
window.location.href = "/chat"
localStorage.setItem('name', name)
localStorage.setItem('password', password)
} else {
alert('not correct :P')
}
}
</script>
</body>
</html>
server_side code:
app.use(express.urlencoded({ extended: true }));
app.post('/api/login', (req, res) => {
console.log(req.body)
// why the output is an empty object {}
res.redirect('/login')
})
I am a frontend dev and am new to backend
#edit: my server code was app.post() but I accidentally put app.get() #because I rewrite the server code not paste it
First, change app.get to app.post to handle the post request.
Second, add the built-in JSON body parser to properly add the "body" property to the request object. app.use(express.json())
To more robustly handle authentication, use passportjs.
Try app.post instead of app.get. See https://expressjs.com/en/guide/routing.html
Your javascript is performing an HTTP POST request, but express is only handling an HTTP GET request.
Try to install and use body-parser
Change app.get() to app.post(). But it will be right to use .put() if you processing /login path.
I'm making a MERN application. I'm fairly new to it, so I'm trying to make everything based on what I know without looking much stuff up, because if I follow tutorials too much I don't remember stuff. Anyway, I've got a component that sends the registration information to the database and everything there is okay. Now I'm trying to check the login.
When I make the "GET" request to a route that I named "/check", nothing happens. If I change it to a "POST" request, things work. Shouldn't it be a "GET" request though since I'm trying to get information from the database?
The Node file:
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const bcrypt = require('bcrypt');
const application = express();
application.use(express.json());
application.use(express.urlencoded({ extended: true }));
const port = process.env.PORT || 8080;
mongoose.connect(process.env.PASSWORD)
.then(console.log('Database connected'))
.catch(error => console.log(error));
const db = mongoose.connection;
application.get('/', (request, response) => {
response.send('Hello World');
});
application.post('/post', (request, response) => {
db.collection('data').insertOne({
name: request.body.username,
password: bcrypt.hashSync(request.body.password, 10),
}).then(console.log('Submission done'));
console.log('POST made');
response.redirect('/');
});
application.get('/check', (request, response) => {
db.collection('data').findOne({
name: request.body.username,
password: bcrypt.compareSync(
request.body.password,
bcrypt.hashSync(request.body.password, 10)
),
});
console.log('The request went through');
response.redirect('/');
});
application.listen(port, () => {
console.log('Listening here...');
});
The React file:
import React from 'react';
export const Login = () => {
return (
<>
<h1 className="text-center">Login</h1>
<div className="row">
<div className="col"></div>
<div className="col text-center">
<form action="/check" method="GET">
<label for="username" name="username">Username: </label>
<input name="username" className="h4" />
<label for="password" name="password">Password: </label>
<input type="password" name="password" className="h4" />
<button>Submit</button>
</form>
</div>
<div className="col"></div>
</div>
</>
);
};
There is difference between the "GET" and "POST" of HTML form element and "GET" and "POST" of node.js .
From Node.js perspective, you can save/send data to database with both POST and GET. However, the situtation is different for form element.
If you use "GET" on the form element, then form will submit all input data to the URL. And on the node.js side, you will need to use req.query to get data on the url, not req.body
So, in your code, you are using "GET" for the Form element but on the node.js file, you are using req.body. This shouldn't work.
Even if you make it work with req.query, the situation will still be totally unsafe, as you openly showing the passwords on the URL.
For more info, on html form attributes, this link can be useful. https://www.w3schools.com/html/html_forms_attributes.asp
you are sending username and password to the server so you should to use POST method
I've been trying to learn NodeJS following
this NodeJs Youtube Tutorial.
I already worked with the Fetch API for a couple of months to get data from WordPress and Google Sheets back ends.
The last videos of the Youtube playlists are about creating a To Do List app with NodeJS and the npm's express, EJS and body-parser.
However, at part 4 of the To do list app, this "teacher" is using jQuery with Ajax to POST data to NodeJS (His jQuery Code Snippet). Since I've only been working with fetch() for AJAX POST requests, i wanted to continue with this method in plain JavaScript.
My ejs file, called todo.ejs, storing the HTML Template of the page looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/assets/style.css">
<!-- Works because of express middleware.
Since we stored the public folder as a static folder,
we can request anything within that folder from the url, such as
127.0.0.1:3000/assets/styles.css
-->
<title>Todo List</title>
</head>
<body>
<h1>My Todo List</h1>
<div id="todo-table">
<form>
<input type="text" name="item" placeholder="Add new item..." required>
<button type="submit">Add Item</button>
</form>
<ul>
<% todos.forEach(todoList =>{ %>
<li> <%= todoList.item %> </li>
<% }) %>
</ul>
</div>
</body>
<script src="/assets/script.js"></script>
</html>
My script.js (linked to the todo.ejs page) looks like this:
document.addEventListener("DOMContentLoaded", function (event) {
let submitButton = document.querySelector("button");
let textField = document.querySelector("input");
submitButton.addEventListener("click", addItem);
function addItem() {
let newItem = textField.value;
let todo = {
item: newItem
};
fetch("/todo", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(todo)
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err))
}
});
And my controller handling all get/post requests, called todoController.js, looks like this:
let bodyParser = require("body-parser");
let urlencodedParser = bodyParser.urlencoded({ extended: false });
// Have some items already in place
let data = [{item: "Get milk"} , {item: "Walk dog"} , {item: "Clean kitchen"}];
module.exports = function (app) {
//Handle get data requests
app.get("/todo", function (req, res) {
res.render("todo", {todos: data});
});
//Handle post data requests (add data)
app.post("/todo", urlencodedParser, function (req, res) {
console.log(req.body);
});
//Handle delete data requests
app.delete("/todo", function (req, res) {
});
};
Now, every time i populate the input field with some text and hit the enter button, my terminal outputs empty objects:
Based on those empty objects, there has to be something wrong that my POST requests are not accepted/sent correctly.
My file tree looks like this:
Anyone who maybe has (probably an obvious) answer to this?
(I know I could just grab his jQuery Ajax code snippet to make it work, but I'm eagerly trying to understand it using plain Javascript)
Thanks in advance to everyone taking time to help me :)
You need to use bodyParser.json instead of bodyParser.urlencoded.
As the names imply, urlencoded will parse url parameters while bodyParser.json will parse json in the body of the request.
I had the same problem but my express's version was > 4.5 so i used :
const express = require('express');
app = express()
app.use(express.json({
type: "*/*"
}))
instead of :
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json())
the problem was fixed by using the parameter {type : '/'} to accept all received content-types.
I've found docs teaching on how to implement Twilio on server-side using Node, however, I couldn't find an end-end example where I can send a SMS coming from my client app.
Can anyone tell me what the implementation would look like to send a post custom SMS from client to server?
Disclaimer my server file is named as app.js and my client file is named as index.js
**1- This is what I have currently setup on my app.js
const express = require('express');
const app = express();
const path = require('path');
const twilio = require('twilio');
const bodyParser = require('body-parser');
//JSON DATA
const guests= require('./public/data/Guests');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
//SET PORT
app.set("port", process.env.PORT || 3000);
//GET JSON DATA
app.get('/data', function(req, res) {
Promise.all([guests])//combine requests into one object
.then(([guests]) => {
res.send({guests});
});
});
//CATCHALL
app.get("/*", function(req,res){
let file = req.params[0] || "/views/index.html";
res.sendFile(path.join(__dirname, "/public/", file));
});
//LISTEN ON PORT
app.listen(app.get("port"), function(){
console.log("Listening on port: " , app.get("port"));
});
let client = new twilio('xxxxxxxxxx', 'xxxxxxxxxxxxx');
app.post('/sms', (request, result) => {
const message = request.body.message;
client.messages.create({
to: +1847820802492359,
from: +8475302725792530 ,
body: message
}).then(() => {
// message sent successfully, redirect to the home page.
res.redirect('/');
}).catch((err) => {
console.error(err);
res.sendStatus(400);
});
});
-2 am trying to process a dynamic message in my index.js. The code works on the DOM properly, it is just the SMS with Twilio that isn't posting the message to the server
$(function() {
$.ajax({
type: "GET",
url: "/data",
success: res => {
//console.log(res);
handleMessage(res);
},
error: err => console.log(err)
});
//message method
let handleMessage = (res) => {
const getFirstName = res.guests.map(name => name.firstName);
//populate drop-down select
let handleSelect = () => {
//adds first names to select dropDown
$.each(getFirstName, function(i, value) {
$('#selectName').append($('<option>').text(value).attr('value', value));
});
};
handleSelect();
let handleSubmit = () => {
$("#form").submit(function(e) {
e.preventDefault();
let name = $('#selectName').val();
let greetGuest = `Welcome ${name}!`;
console.log(greetGuest);
//append to Dom
$('.showMessage').append(`<div class="newMessage"><span>${greetGuest}</span></div>`);
});
};
handleSubmit()
};
});
-3 HTML form
<form id="form" action="/sms" method="POST">
<label>
<label for=selectName>Guest
<select id="selectName" class="select " name="sms">
</select>
</label>
</label>
<input type="submit" value="send" class="btn btn-success" />
</form>
Am I having an asynchronicity issue here?
Twilio developer evangelist here.
I can give you a basic example here, which should give you a good idea of how to achieve this. I'll start with the server side, which you already have the basics of.
Firstly, I would recommend you use a POST request rather than a GET, simply because GETs can be easily repeated by users or cached by proxies. I assume you are using Express as the web application server. You will also need the body-parser module to read the data that we send from the client side.
const Twilio = require('twilio');
const express = require('express');
const bodyParser = require('body-parser');
const app = new express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
const twilio = new Twilio(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN);
app.post('/messages', (request, result) => {
const message = request.body.message;
twilio.messages.create({
to: TO_NUMBER,
from: FROM_NUMBER,
body: message
}).then(() => {
// message sent successfully, redirect to the home page.
res.redirect('/');
}).catch((err) => {
console.error(err);
res.sendStatus(400);
});
});
app.listen(3000);
This sets up a server which is serving static files from a public directory and then has one endpoint, POST to /messages, that sends a message.
We now need to create the client side. I shall do this in HTML only for simplicity. You need a form that will POST to the /messages endpoint with, in this case, a single field for the message. I've included a textarea to write the message in and a button to submit the form. If you save this as index.html in the public directory where you run the application from then it should work.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Send a message!</title>
</head>
<body>
<h1>Send a message!</h1>
<form action="/messages" method="POST">
<label for="message">What would you like to send?</label>
<textarea name="message" id="message"></textarea>
<button type="submit">Send!</button>
</form>
</body>
</html>
Let me know if that helps at all.
Update
So you're looking to make the request to the server using Ajax so your page doesn't reload and you can display a different message. Your current form seems to have removed the message textarea that I added, I'll put it back in again. I assume you also want to send the message to whichever guest you are welcoming at the time, but I don't know how that works in your system, so I'm going to avoid that for now and hopefully you can sort it out.
So, if you update your form to something like this:
<form id="form" action="/sms" method="POST">
<label>
<label for=selectName>Guest
<select id="selectName" class="select " name="sms">
</select>
</label>
</label>
<label for="message">Message</label>
<textarea id="message" name="message"></textarea>
<input type="submit" value="send" class="btn btn-success" />
</form>
Then you need to add to your JavaScript a way to actually submit the form (since you are preventing the submission with e.preventDefault().
const $form = $('#form');
$form.submit(function(e) {
e.preventDefault();
let name = $('#selectName').val();
let greetGuest = `Welcome ${name}!`;
console.log(greetGuest);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function(data) {
console.log("The message has been sent");
},
error: function() {
console.error("The message couldn't be sent");
console.error(...arguments);
}
})
//append to Dom
$('.showMessage').append(
`<div class="newMessage"><span>${greetGuest}</span></div>`
);
});
In this case we are hooking into the callback for the submit event to make a new $.ajax request to the form's action, using the method (POST), and including the form data (which we get from $form.serialize()). We then setup success and error callbacks as you've done at the top of the function.
Let me know if this helps.