Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a HTML form as follows:
<form id="loginForm" name="loginForm">
<div class="form-group">
<input type="username" class="form-control" id="username" name="username" placeholder="Your username..." >
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Your password...">
</div>
<button class="btn btn-primary btn-block btn-round" id="loginButton" type="submit">Login</button>
</form>
and a Javascript file containing the following code to make an AJAX request:
//credits to #lndgalante
if (typeof window !== 'undefined') {
window.addEventListener('load', () => {
const form = document.getElementById('loginForm');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const elements = event.target;
const username = elements.username.value;
const password = elements.password.value;
const dataToSend = { username, password };
try {
console.log(JSON.stringify(dataToSend)); //To check variables are being passed correctly
return await fetch('/login', {
method: 'POST',
body: JSON.stringify(dataToSend),
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
console.log(error);
}
});
});
};
and a node.js file with the corresponding POST route:
app.post('/login', async (req, res) => {
try {
const username = req.body.username;
const password = req.body.password;
console.log(username, password, req.body); //To check variables are being passed correctly
...
}
});
But the problem is,
console.log(JSON.stringify(dataToSend)); returns {"username":"username1","password":"password1"} //or whatever the user input is as expected, whereas
console.log(username, password, req.body) returns undefined undefined {}.
Does anyone know what I'm doing wrong?
Edit: I am using const app = express(); and I have app.use(bodyParser.urlencoded({ extended: true })); in my node.js file.
You must use a body parser, otherwise your NodeJS application will not know how to interpret your string received in the request body.
npm install --save body-parser
and
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
or
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
So your code will run propperly.
More details here: How to retrieve POST query parameters?
Assuming you're using Express.js (you should probably tag the question) you need to make sure you use the express.json() (or bodyParser.json()) middleware for JSON body parsing.
const app = express();
app.use(express.json());
app.post('/login', ...);
Your client-side code is correct.
I have app.use(bodyParser.urlencoded({ extended: true })); in my node.js file.
You're POSTing JSON, not URL Encoded data.
You need a JSON parser.
app.use(bodyParser.json());
… or to post URL Encoded data:
Related
I tried to post the form with Javascript fetch API, but it doesn't work. Where am I making mistakes?
the HTML form :
<form id="my-form" method="post" action="/" enctype="multipart/form-data">
<input type="text" name="name" id="ok">
<input type="text" name="pro" id="okpro">
<button type="submit"> Submit it </button>
</form>
Javascript codes I wrote in it :
const form = document.getElementById('my-form');
form.onsubmit = async function(e){
e.preventDefault()
const formData = new FormData(form)
for (const it of formData) {
console.log(it[0], it[1]);
}
const response = await fetch('/', {method: 'POST', body: formData})
const result = await response.json()
console.log(result);
}
note: I tried with form.addEventListener also, nothing changes :(
and the post route from nodeJs :
route.post("/", (req, res) => { console.log("Our Body", req.body)
res.status(200).json({
res: req.body, }) })
If you try to use/parse req.body, I highly recommend to use a package like body-parser.
Here's an example configuration:
const bodyParser = require("body-parser");
//some code, e.g. imports or other use() calls
app.use(
bodyParser.urlencoded({
extended: false,
}),
); //for form actions, e.g. posting directly
app.use(bodyParser.json()) //for normal requests like in your example
//Routes
Then, your req.body should have data. Make sure to include the .use() function above your existing requests.
Here is a link to body-parser on npm: https://npmjs.com/body-parser
As you seem to only be submitting text, you can remove the enctype from your form.
Hope it helps :)
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 made a simple nodejs server which serves a html page to the user.The page contains a input text box of userID. When the user presses the button submit, I take that userID entered by the user and put it in form Data and send it to my server function (submitForTest) through POST method.
Now, inside my function of nodejs which handles submitForTest, I tried to access the userID , but I was getting res.body as {} , so not able to figure out how to access userID here.
Can anyone please point what I need to get the userID at my node js code.
My HTML file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<label>User ID</label>
<div>
<input type="text" id="userid" >
</div>
</div>
<div>
<div>
<button type="submit" onclick="submitForTest()">Submit</button>
</div>
</div>
<script type="text/javascript">
function submitForTest()
{
var userID = document.getElementById('userid').value;
let formData = new FormData();
formData.append("userID", userID);
//alert("hello");
fetch('http://MY-SERVER:3000/submitForTest', {method: "POST", body: formData});
}
</script>
</body>
</html>
My Node js file :
'use strict'
const fs = require("fs")
const express = require('express')
var path = require('path')
const app = express()
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var jsonParser = bodyParser.json();
app.get('/',function(req,res) {
res.sendFile('small.html');
});
app.post('/submitForTest', function(req, res) {
//want to print userID here .. but the below is coming as {} here ..
console.log(req.body);
})
// Tell our app to listen on port 3000
app.listen(3000, function (err) {
if (err) {
throw err;
}
console.log('Server started on port 3000')
})
Please help.
Regards
The problem is FormData is sending body encoded as multipart/form-data. You'll have to add middleware able to handle multipart body format. Busboy or multer for example.
Example of using multer to upload a file and send userID field:
// --- form
<form action="/submitForTest" enctype="multipart/form-data" method="post">
<input type="file" name="uploaded_file">
<input type="text" name="userID">
<input type="submit" value="Submit">
</form>
// --- server
var multer = require('multer')
var upload = multer({ dest: './uploads/' }) // where the uploaded files will be stored
app.post('/submitForTest', upload.single('uploaded_file'), function (req, res) {
// req.file is the name of your file in the form above, here 'uploaded_file'
// req.body will hold the text fields, if there were any
console.log(req.file, req.body)
});
Or to send your data in urlencoded or json format. Something like that for json for example:
function submitForTest()
{
var userID = document.getElementById('userid').value;
fetch('http://MY-SERVER:3000/submitForTest', {
method: "POST",
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({ userID }),
});
}
This question already has answers here:
How to access POST form fields in Express
(24 answers)
Closed 2 years ago.
I have a simple form:
<form method="POST">
<div class="form-group">
<label>Email address</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
and I have a simple model:
const User = mongoose.model('User', {
email: {
type: String,
},
password: {
type: String,
}
});
and a simple post method
.post(async (req, res) => {
console.log(req.body);
const user = new User(req.body);
try {
const saveUser = await user.save();
res.send(saveUser);
} catch (error) {
res.send(error);
}
}
And yet, when i submit my form at the HTML file i get back an empty object.. i've tried every single one of SO solutions and none of them work for me.
NOTE: that i am using a JSON parser: app.use(express.json());.
please help ?
Your form is not sending JSON encoded data. Instead it uses application/x-www-form-urlencoded. Longer read Therefore you either need a bodyParser or you send the form data JSON encoded.
Try converting the user instance to a JSON string: res.send(saveUser.toJSON());
Make sure you have body-parser installed and imported to your project. npm i body-parser
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: true }));
This is the method I am familiar when it comes to create a new entry
let email = req.body.email
let password = req.body.password
let user = {email: email, password: password}
User.create(user, (err, newUser) => {
if(err) // handle err
else // do something - redirect, etc..
})
Solved:
app.use(express.urlencoded({
extended: true
}));