I'm doing a React App + Express server,
I want to get in a route /info in my server all the infos from a form in a client,
But when I console log "req.body" in the server, I always get an empty object (see Express code below),
I tried to use body-parser but nothing changes, I don't see where's the issue,
Can somebody help me please ?
React code :
async function getResults(e) {
e.preventDefault();
const info = {
minimumPrice,
maximumPrice
};
console.log("info ", info);
try {
const data = await axios.get("http://localhost:5000/info", info);
console.log("data ", data);
setResults(data.data);
console.log("results ", data.data);
} catch (e) {
console.error(e);
}
}
<form onSubmit={getResults} autoComplete="off" method="get">
<div className="row">
<div className="input-field col s12">
<input
id="minimum-price"
type="number"
name="minimumPrice"
placeholder="Entrez votre prix minimum"
value={minimumPrice}
onChange={e => setMinimumPrice(e.target.value)}
style={{ backgroundColor: "transparent !important" }}
required
/>
<label htmlFor="email">Prix minimum</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<input
id="maximum-price"
type="number"
name="maximumPrice"
placeholder="Entrez votre prix maximum"
value={maximumPrice}
onChange={e => setMaximumPrice(e.target.value)}
style={{ backgroundColor: "transparent !important" }}
required
/>
<label htmlFor="email">Prix maximum</label>
</div>
</div>
<div className="row">
<div className="col s12" style={{ textAlign: "center" }}>
<button
className="btn waves-effect waves-light"
type="submit"
name="action"
>
Rechercher
<i className="material-icons right">send</i>
</button>
</div>
</div>
</form>
Express code :
const express = require("express");
const app = express();
const leboncoin = require("leboncoin-api");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
app.get("/info", (req, res) => {
console.log("body ", req.body); <---------- ALWAYS AN EMPTY OBJECT
}
You are making a get request with axios. The parameters sent with get request are available in req.query.
Parameters passed with post request are received in req.body.
Related
I am using boostrap (via MDB 4) and am trying to get the contact form to work. I have the form presenting as expected. It contains the following button outside the </form> tag
<a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a>
The opening line of the form is:
<form id="contact-form" name="contact-form" action="/contact" method="POST">
I am trying to understand how I get the form contents to nodejs and have the following in my Express routes
app.post('/contact', function(req, res){
console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.subject);
console.log(req.body.message);
// code to store here later
});
I know this I am hitting this block as I can console out text from within the route but I get an error every time:
TypeError: Cannot read property 'name' of undefined
All the examples seem to use PHP but I would have thought nodejs would be more than enough for this? I don't have PHP on the box and would rather avoid it if I can stay in nodejs. Anyone got some pointers for me?
It might be worth noting that jquery is used but I don't know if that links in here? The following is at the foot of my html
<script type="text/javascript" src="js/jquery.min.js"></script>
Solved by adding the following to my index.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
Now when I console.log(req.body); is get:
{
name: 'name',
email: 'name#x.y',
subject: 'test',
message: 'test'
}
I created solution for you:
//connect express
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var partials = require('express-partials');
var app = express();
app.use(express.json());
app.use(partials());
app.use(express.urlencoded({ extended: false }));
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
//top level routing
app.get('/', (req, res) => {
res.render('index.ejs')
});
app.post('/contact', function(req, res){
res.render('thanks.ejs', {body: req.body})
});
//start server
var http = require('http');
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
<!--- start index.ejs -->
<form action="/contact" method="post" class="form-signin">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="name">Subject</label>
<input type="text" class="form-control" name="subject" placeholder="Enter subject">
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea type="text" class="form-control" name="message" placeholder="Enter message"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!--- end index.ejs -->
<!--- start thanks.ejs--->
<%=JSON.stringify(body)%>
<!--end thanks.ejs --->
<!--- start layout.ejs --->
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="content">
<%-body -%>
</div>
</div>
</body>
</html>
<!--- end layout.ejs --->
My answer is based on this resource https://exceed-team.com/tech/form-submit-with-bootstrap-and-nodejs
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");
});
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"
}
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.
Being a newbie to Node js and MongoDb, I created a simple form using HTML to get feedbacks. So when I submit my form, I am getting an output that my data is saved, but essential I am not able to see any data in the database. Below is the full code.
HTML:
<form action="/feedback" method="post">
Name <input type = "Name" name=value=""> <br><br>
Roll No <input type = "text" value=""> <br><br>
Meal <input type = "text" value=""> <br><br>
Quality <input type = "text" value=""> <br><br>
Comments <input type = "text" value=""> <br> <br>
<input type = "submit" value ="submit">
</form>
app.js:
const express = require('express');
const bodyParser=require('body-parser')
const mongoose = require('mongoose');
mongoose.Promise=global.Promise;
var app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
mongoose.connect('mongodb://localhost:27017/feedback');
var feebackschema = new mongoose.Schema({
Name: String,
Rollno: String,
Meal: String,
Quality: String,
Comments: String
});
var feed = mongoose.model('feed',feebackschema);
module.exports=feed
app.get("/", function(req,res){
res.sendFile(__dirname+"/index.html");
})
app.post("/feedback", function(req,res){
var mydata=new feed(req.body);
mydata.save()
.then(item =>{
res.send("Data saved");
})
.catch(err=>{
res.send("Data not saved");
})
})
app.listen(4000, function(){
console.log("Server listening on 4000");
})
EDIT:
HTML
<form action="/feedback" method="post">
Name <input type = "Name" name= "name" value=""> <br><br>
Roll No <input type = "text" name="rollno" value=""> <br><br>
Meal <input type = "text" name="Meal" value=""> <br><br>
Quality <input type = "text" name="quality" value=""> <br><br>
Comments <input type = "text" name="comments" value=""> <br> <br>
<input type = "submit" value ="submit">
</form>