How to get POST data in request? - node.js

I'm using Express+Node.js now. I need to extract POST data from a request to make Log-in process.
I want to get POST data in request but there was nothing in req.body when I ran my code.(Always return {} )
I'm relatively new to NodeJs, so precise help is welcome. Please help me.
var express = require('express');
var router = express.Router();
var bodyparser=require('body-parser');
var crypto=require('crypto');
var passport=require('passport');
var localStrategy=require('passport-local').Strategy;
var mysql=require('mysql');
router.use(bodyparser.json());
router.use(passport.initialize());
router.use(passport.session());
var config={
///config
};
const conn = new mysql.createConnection(config);
conn.connect(function(err){
if(err){
console.log('Cannot Connect to database : ');
throw err;
}
else{
console.log('Success to connect database');
}
});
var isAuthenticated =function(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.redirect('/');
}
router.post('/login',function(req,res,next){
console.log(req.body);
});
module.exports=router;
html form code
<form class="login100-form validate-form" method="post" action="/login">
<div class="wrap-input100 validate-input" data-validate = "이메일 양식 확인">
<input class="input100" type="text" name="username">
<span class="focus-input100" data-placeholder="Email"></span>
</div>
<div class="wrap-input100 validate-input" data-validate="비밀번호 양식 확인">
<span class="btn-show-pass">
<i class="zmdi zmdi-eye"></i>
</span>
<input class="input100" type="password" name="password">
<span class="focus-input100" data-placeholder="Password"></span>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<button class="login100-form-btn">
Login
</button>
</div>
</div>
</form>

you need to send a body in your request, something like the postman tool can help you.
You need to add a body to your request and send it to your http://localhost: 3000

Use POSTMAN, insert url like this http://10.10.0.1:3000/user/login
in Body section select raw type Json
then insert
{
"email_id" : "abc123#xyz.in",
"password" : "Test#123"
}

Related

Iam trying to submit an update form via put method but doesnt work [duplicate]

I have the following route in my express application:
router.get('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(searchQuery)
Address.findOne(searchQuery)
.then(address => {
res.render('myForm', {address:address});
})
.catch(err => {
console.log(err);
});
});
and my form is:
<form action="/edit/<%= address.id %>?_method=put" method="POST">
<input type="hidden" name="_method" value="PUT">
<br>
<input type="text" value="<%= address.name %>" name="name" class="form-control">
<br>
<input type="text" value="<%= address.email %>" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
It works correctly, I can see the data getting form the mongodb into myForm. Now after I update some data in this form and click the udpdate button i get : Cannot POST /edit/62185a7efd51425bbf43e21a
Noting that I have the following route:
router.put('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(`searchQuery = ${searchQuery}`)
Address.updateOne(searchQuery, {$set: {
name: _.extend(name, req.body),
email: req.body.email,
}})
.then(address => {
res.redirect('/');
})
.catch(err => {
res.redirect('/');
});
});
It looks like express call the get and not the put in my case. Any suggestion?
The browser itself will only do GET and PUT from a <form>. So, your browser is sending a POST and your server doesn't have a handler for that POST.
The ?_method=put that you added to your URL looks like you're hoping to use some sort of method conversion or override tool on the server so that it will recognize that form POST as if it were a PUT. You don't show any server-side code to recognize that override query parameter so apparently your server is just receiving the POST and doesn't have a handler and thus you get the error CANNOT POST /edit/62185a7efd51425bbf43e21a.
There are several different middleware solutions that can perform this override. Here's one from Express: http://expressjs.com/en/resources/middleware/method-override.html and you can see how to deploy/configure it in that document.
Basically, you would install the module with:
npm install method-override
and then add this to your server:
const methodOverride = require('method-override')
// override with POST having ?_method=PUT
app.use(methodOverride('_method'));
This will look at incoming POST requests with the ?_method=PUT query string and will modify the method per the parameter in the query string so that app.put() will then match it.
This is to be used when the client can only do GET or POST and can't do other useful methods such as PUT or DELETE.
As a demonstration, this simple app works and outputs got it! back to the browser and /edit/123456789?_method=put in the server console when I press the Update User button in the HTML form.
const app = require('express')();
const path = require('path');
const methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
app.put('/edit/:id', (req, res) => {
console.log(req.url);
res.send("got it!");
});
app.listen(80);
And, temp.html is this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/edit/123456789?_method=put" method="POST">
<br>
<input type="text" value="hello" name="name" class="form-control">
<br>
<input type="text" value="hello#gmail.com" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
</body>
</html>
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.
Note: you must change the method in side form tag to PUT
<form action="/edit/<%= address.id %>" method="put">
//Backend.js
router.route('/edit/:id')
.get((req, res) => {
res.send('Get a random book')
})
.put((req, res) => {
res.send('Update the book')
})

Why express call my get route and not my put route?

I have the following route in my express application:
router.get('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(searchQuery)
Address.findOne(searchQuery)
.then(address => {
res.render('myForm', {address:address});
})
.catch(err => {
console.log(err);
});
});
and my form is:
<form action="/edit/<%= address.id %>?_method=put" method="POST">
<input type="hidden" name="_method" value="PUT">
<br>
<input type="text" value="<%= address.name %>" name="name" class="form-control">
<br>
<input type="text" value="<%= address.email %>" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
It works correctly, I can see the data getting form the mongodb into myForm. Now after I update some data in this form and click the udpdate button i get : Cannot POST /edit/62185a7efd51425bbf43e21a
Noting that I have the following route:
router.put('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(`searchQuery = ${searchQuery}`)
Address.updateOne(searchQuery, {$set: {
name: _.extend(name, req.body),
email: req.body.email,
}})
.then(address => {
res.redirect('/');
})
.catch(err => {
res.redirect('/');
});
});
It looks like express call the get and not the put in my case. Any suggestion?
The browser itself will only do GET and PUT from a <form>. So, your browser is sending a POST and your server doesn't have a handler for that POST.
The ?_method=put that you added to your URL looks like you're hoping to use some sort of method conversion or override tool on the server so that it will recognize that form POST as if it were a PUT. You don't show any server-side code to recognize that override query parameter so apparently your server is just receiving the POST and doesn't have a handler and thus you get the error CANNOT POST /edit/62185a7efd51425bbf43e21a.
There are several different middleware solutions that can perform this override. Here's one from Express: http://expressjs.com/en/resources/middleware/method-override.html and you can see how to deploy/configure it in that document.
Basically, you would install the module with:
npm install method-override
and then add this to your server:
const methodOverride = require('method-override')
// override with POST having ?_method=PUT
app.use(methodOverride('_method'));
This will look at incoming POST requests with the ?_method=PUT query string and will modify the method per the parameter in the query string so that app.put() will then match it.
This is to be used when the client can only do GET or POST and can't do other useful methods such as PUT or DELETE.
As a demonstration, this simple app works and outputs got it! back to the browser and /edit/123456789?_method=put in the server console when I press the Update User button in the HTML form.
const app = require('express')();
const path = require('path');
const methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
app.put('/edit/:id', (req, res) => {
console.log(req.url);
res.send("got it!");
});
app.listen(80);
And, temp.html is this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/edit/123456789?_method=put" method="POST">
<br>
<input type="text" value="hello" name="name" class="form-control">
<br>
<input type="text" value="hello#gmail.com" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
</body>
</html>
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.
Note: you must change the method in side form tag to PUT
<form action="/edit/<%= address.id %>" method="put">
//Backend.js
router.route('/edit/:id')
.get((req, res) => {
res.send('Get a random book')
})
.put((req, res) => {
res.send('Update the book')
})

'cannot get addfriend' in express while using postrequest

This is my code app.js code
var express = require("express");
var app = express();
var bp = require("body-parser");
app.use(bp.urlencoded({extended: true}));
var friends = ["babba","lkshjk","kfhkd"];
app.get("/",function(req,res){
res.send("homepage");
});
app.get("/friends",function(req,res){
res.render("friends.ejs",{friends : friends});
});
app.post("/addfriends",function(req,res){
res.send("works fine");
});
var server = app.listen(2700 ,function() {
console.log("started");
});
and this is friends.ejs code
<h1>
friends list
</h1>
<% friends.forEach(function(friend){ %>
<li> <%= friend %> </li>
<% }); %>
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
i just need "works fine " in my '/addfriend'
but i am getting
cannot get /addfriend in chrome
this works fine in postman when i try to debug
Your form have to point to the express route.
It should be:
<form action="/addfriends" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
Instead of
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
You should declare your route equal you did in express route:
app.post("/addfriends",function(req,res){
res.send("works fine");
});

"What is causing this 'incorrect form submission' response to my simple node post request?"

Making a signup page for an app I'm going to build later. Just created a simple as can be node server, and it's running on port 3000. I created a React app with a simple form interface, running on port 3001. The user fills in the form and hits the register button, and this should send an email and password to the post route of /register.
But I get "incorrect form submission" every time. It looks like just a json object in the network pane "{email: dummy#email, password: 123}", so I'm not sure what this means...
onSubmitRegister = () => {
fetch('http://localhost:3000/register', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then(response => response.json())
.then(data => console.log(data));
}
The node server looks like this:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", (req, res) => {
res.send("Hello");
})
app.post("/register", (req, res) => {
console.log(req.body);
})
app.listen(3000, () => {
console.log("Server started on port 3000");
});
For now, I just want it to console log the req.body, so I know everything is working OK before I go on to build a MongoDB database and start adding documents to collections. Stack Overflow and other forum threads I've googled suggest checking the headers are correct. This looks OK to me. Am I missing something?
EDIT: This is what the form looks like, the entire render function:
render(){
return(
<div>
<div className="text-center">
<form className="form-signin">
<h1 className="h3 mb-3 font-weight-normal">Ohaii Sign Up</h1>
<label for="inputEmail" className="sr-only">Email address</label>
<input
type="email"
id="inputEmail"
className="form-control"
placeholder="Email address"
required=""
autofocus=""
onChange={this.onEmailChange}
/>
<label for="inputPassword" className="sr-only">Password</label>
<input
type="password"
id="inputPassword"
className="form-control"
placeholder="Password"
required=""/>
<label for="inputPassword" className="sr-only">Password</label>
<input
type="password"
id="confirmPassword"
className="form-control"
placeholder="Confirm Password"
required=""
onChange={this.onPasswordChange}
/>
<div className="btn btn-block btn-social btn-google" style={{'color': '#fff'}}>
<span className="fa fa-google"></span> Sign Up with Google
</div>
<div className="btn btn-block btn-social btn-facebook" style={{'color': '#fff'}}>
<span className="fa fa-facebook"></span> Sign Up with Facebook
</div>
</form>
</div>
<button
onClick={this.onSubmitRegister}
className="btn btn-lg btn-primary btn-block"
>Register</button>
</div>
)
}
As you are sending JSON data (both your body is JSON and you are setting the JSON content type), I would recommend to change the bodyParser middleware to:
app.use(bodyParser.json());
At least, in my quick test I was then able to send data from the browser and saw it on the server. With bodyParser.urlencoded that was not the case, however, I did not get the same error as you did.
In addition, you should return some response from the server, for example, I used:
app.post("/register", (req, res) => {
console.log(req.body);
res.end("{}");
});
Was a problem specific to my environment. Just cleared the npm cache and that fixed it.

Sending email to several recipients via nodemailer doesn't work

I tried looking for different answers but they didn't work. I don't receive the email in my gmail account when I am trying to send it, I am just getting it in my Ethereal account.
This is my server code:
const express = require('express');
const path = require('path');
const cons = require('consolidate');
const bodyParser = require('body-parser');
const nodemailer = require("nodemailer");
const app = express();
app.engine('html', cons.swig)
app.set('../public', path.join(__dirname, 'public'));
app.use('../src/css', express.static(path.join(__dirname, 'src/css')));
app.use('../src/js', express.static(path.join(__dirname, 'src/js')));
app.use(bodyParser.urlencoded({ extended: false}));
app.use(bodyParser.json());
app.post('/send',(req,res) => {
const output = `
<p>name of client: ${req.body.name}</p>
`;
let transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false,
auth: {
user: "*****#ethereal.email",
pass: "********"
},
tls: {
rejectUnauthorized: false
}
});
let mailOptions = {
from: `${req.body.email}`,
to: "******#gmail.com",
subject: "Node contact request",
text: "Hello world?",
html: output
};
transporter.sendMail(mailOptions, (error, info) => {
if(error) {
return console.log(error);
}
console.log("Message sent: %s", info.messageId);
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
res.render('index')
});
});
app.listen(5000);
I am using react app for my front-end(e-commerce), and I want that after sending the email the client will see a message saying "The email has been sent" (the location doesn't really matter for now). How can I do it after submitting the form? Right now the client is directing to localhost:5000/send instead of staying at the same page.
This is my react code:
import React from 'react';
const contact = () => {
return (
<form className="contact" action="http://localhost:5000/send" method="post">
<div className="contact-topFields">
<div className="contact-topFields-email">
<input
className="contact-topFields-email-input"
type="email"
name="email"
required/>
<ion-icon id="email-icon" name="mail"></ion-icon>
<p className="contact-topFields-email-text">Email</p>
</div>
<div className="contact-topFields-name">
<input
className="contact-topFields-name-input"
type="text"
name="name"
required/>
<ion-icon id="name-icon" name="person"></ion-icon>
<p className="contact-topFields-name-text">Name</p>
</div>
</div>
<div className="contact-bottomFields">
<div className="contact-bottomFields-phone">
<input
className="contact-bottomFields-phone-input"
type="text"
name="phonenumber"
required/>
<ion-icon id="phone-icon" name="call"></ion-icon>
<p className="contact-topFields-phone-text">phone</p>
</div>
</div>
<div className="contact-text">
<textarea className="contact-text-textarea" name="message" required></textarea>
</div>
<button className="contact-submitButton" type="submit">send </button>
</form>
)
}
export default contact;
To prevent the page being directed to localhost:5000/send:
In order to trigger sending the email while keep the user's view unchanged, you may want to override the form's submit function.
For example, you may want to do this in your JSX code:
<form className="contact" onSubmit={{this.handleSubmit}}>
<- whatever inside form ->
</form>
Then you may want to define a function handleSubmit:
function handleSubmit (evt) {
evt.preventDefault() // this is used to prevent ui from being directed
// Do http request here, use a http agent such as fetch(), axios() etc etc.
}

Resources