I am trying to post data from my react. Backend - express.
Here is backend code:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var mongoose = require("mongoose");
var expressSanitizer = require("express-sanitizer");
mongoose.connect("mongodb://localhost/blog-react");
//app config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
//must be after parser
app.use(expressSanitizer());
app.use(methodOverride("_method"));
//schema config
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
//it should be date. With default value now.
created: {
type: Date, default: Date.now
}
});
var Blog = mongoose.model("Blog", blogSchema);
function handle500(response, error){
console.log(error.stack);
response.status(500);
response.json({error: "error: internal server error"});
}
app.post("/api/blogs", function(request, response){
var blog = {
title: request.sanitize(request.body.title),
image: request.sanitize(request.body.image),
body: request.sanitize(request.body.body)
};
console.log(request.body);
Blog.create(blog, function(error, newBlog){
if(error){
console.log("inside post handler ERROR")
handle500(response, error);
}
else{
console.log("inside post handler OK")
response.json({status: "success"});
}
});
});
React code:
var requestUrl = "/api/blogs";
var blog = {
title: "a",
image: "b",
body: "c"
}
axios.post(requestUrl, blog)
.then(function(response){
console.log("success",response.data)
})
.catch(function(response){
console.log("error", response);
});
When I post data via axios - request.body is always {}
But if I post data via regular form - all is correct - request.body contains all expected data.
What am I doing wrong with axios?
You are missing one middleware, bodyParser.json(). Add it to your configuration.
mongoose.connect("mongodb://localhost/blog-react");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.json()); // <--- Here
app.use(bodyParser.urlencoded({extended: true}));
For people using Express>=4.16, bodyParser has been changed to the following:
app.use(express.json());
For me the issue was valid JSON format including double quotes on the variables.
This did not work
const res = await axios.post(serverPath + "/user/login", {
email: email,
password: password,
});
This DID work (with double quotes around email and password)
const res = await axios.post(serverPath + "/user/login", {
"email": email,
"password": password,
});
It looks like you only have two points left to make it work :
one : the http method should be set to POST instead of GET since you want to send something.
two : you can then add the http header (like what you did with the authorization header) Content-Type: 'application/json`
On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.
I suppose your server is using express, here is how you will do it with express :
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */
Related
My req.body shows {} always even though I am using body-parser in my code
user model
const userSchema = new mongoose.Schema({
email: {
type: String,
required:true,
index:true,
},
password: {
type: String,
required: true
}
},{timestamps:true});
module.exports = mongoose.model('User', userSchema);
routes
const express= require('express');
const router = express.Router();
const {currentUser} = require("../controllers/user");
router.post('/current-user', currentUser);
module.exports = router;
Controllers
const User = require("../models/user");
exports.currentUser = async (req, res) => {
const {email} = req.body
console.log(email)
// console.log(req.query)
await User.findOne({email}).then((user) => {
if (!user) {
// console.log(user);
return res.status(401).json({
error: 'User not found!'
});
}
res.json({
data:"SUCCESS"
})
})
}
I am getting an error: user not found even if the email id exists.
If I console.log(req.body)
=> Output:
{}
console.log(req.body.email)
=> Output:
undefined
Please help me fix this.
You might want to use bodyPrser() middleware.
You can read more about it here
npm i body-parser --save
Then, in your server.js or app.js file
const bodyParser = require('body-parser');
const app = express();
app.use(router()); //your user defined router middleware
app.use(bodyParser.json()); //this is a bodyparser middleware to read/extract the
//data from req.body
Please dont use body parser its already deprecated, since you are already using express there is a built in middleware for body-parser like
const app = express()
app.use(express.json({ limit: '50mb' }))
app.use(express.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000 }))
this will do work of body-parser.
Other thing, can you tell us what are you sending in request since it is a post request and you might be sending an empty object thats why you are getting {} in req.body?
I can see you are extracting email from it but if you can provide sample request, it will definitely help.
I am self learning nodeJS, Now I tried to insert data in MongoDB and this my goal
insert values in here and once submit button is clicked, should save the data successfully to mongodb and this should return a successful message.
But this is the error
TypeError: Cannot read property 'location' of undefined
Here are the code snippets
const express = require('express');
const dotenv = require("dotenv").config();
const address = process.argv[2];
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const app = express();
//INSERT TO MONGO DB
//connect to mongo db
mongoose.connect('mongodb://localhost/weathertest2');
mongoose.Promise = global.Promise;
//create weather schema
const WeatherSchema = new Schema({
location:{
type: String
},
temperature:{
type: String
},
observationTime:{
type: String
}
});
const Weather = mongoose.model('weather', WeatherSchema);
// post request
app.post('/new', function(req, res){
new Weather({
location : req.body.location,
temperature: req.body.temperature,
observationTime : req.body.observationTime
}).save(function(err, doc){
if(err) res.json(err);
else res.send('Successfully inserted!');
});
});
// listen for request
app.listen(process.env.port || 9000, function(){
console.log('now listening for testing request');
});
app.use(express.static('public'));
Try using the body-parser middleware alongside with express:
https://www.npmjs.com/package/body-parser
const bodyParser = require("body-parser");
/*
* Parses the text as URL encoded data (which is how browsers tend to send
* form data from regular forms set to POST) and
* exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({ extended: true }));
This way the data from the form should be included in the request body (req.body.location)
It seems that the body of the request is undefined. This might be because express isn't parsing the request body correctly. The solution is probably to use a body parser.
npm install --save body-parser
Then import body-parser into your file:
const bodyParser = require('body-parser')
Then place this line before the "/new" handler:
app.use(bodyParser)
Here is my HTML with the form piece.
<form [formGroup]="form" (submit)="onSave()" *ngIf="!isLoading">
<mat-form-field>
<input matInput type="text" formControlName="name" placeholder="Organization Name">
Here is the code for onSave() from my component.ts file.
onSave() {
if (this.form.invalid) {
return;
}
this.isLoading = true;
if (this.mode === "create") {
this.objsService.add(
this.form.value.name
);
} else {
this.objsService.update(
this.id,
this.form.value.name
);
}
this.form.reset();
}
Here is the add() function from my service.
/* #region Create of CRUD */
add(name: string) {
const objData = new FormData();
objData.append("name", name);
this.http
.post<{ message: string; obj: Organization }>(
'http://localhost:3000/api/organizations',
objData
)
.subscribe(responseData => {
this.router.navigate(["/organizations"]);
});
}
/* #endregion */
And lastly here is my .post to the router in mp api.
/* #region Create of CRUD */
router.post('', (req, res, next) => {
console.log('req.body.name: ' + req.body.name);
const obj = new objModel({
name: req.body.name
});
obj.save().then(createdObj => {
res.status(201).json({
message: capitalize(plural) + ' added successfully',
obj: {
...createdObj,
id: createdObj._id
}
});
});
});
/* #endregion */
As you can see in my api I''m running "console.log('req.body.name: ' + req.body.name);", it's output is "req.body.name: undefined". How could this be? What am I missing?
In my service I ended up add the following line.
add(name: string) {
const objData = new FormData();
objData.append('name', name);
console.log(name);
console.log(objData);
Here's what showed up in the console.
dfgasdfg
FormData {}
__proto__: FormData
append: ƒ append()
...
values: ƒ values()
arguments: (...)
...
name: "values"
__proto__: ƒ ()
...
name: ""
name: "" should be name: "dfgasdfg". Is the .append syntax incorrect?
Here's my server.js file. I did include body-parser. Did I implement it improperly?
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const postsRoutes = require("./routes/posts");
const organizationsRoutes = require("./routes/organizations");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Thank you in advance!
i think you missing body-parser middleware in node api that's why you getting undefined in req.
const bodyParser = require('body-parser');
const app = express();
app.use(express.json());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
please try to use above express middleware in server.js root file, to get data in req.body object.
Ok, I'm an idiot. I needed to use the following.
app.use(bodyParser.urlencoded({extended: true}));
I was using:
app.use(bodyParser.urlencoded({extended: false}));
Thanks for the direction!!!!
P.S.
Ok, I take it back. It wasn't a permanent fix. I am running express 6.9.0, doesn't express 4.16+ have it's own parser? I changed my code to now have this:
app.use(express.json());
app.use(express.urlencoded());
In my route for the API it looks like it's still not populating req.body.name with the value from the form.
Using this:
console.log('req.body.name: ' + req.body.name);
I get this:
req.body.name: undefined
I am using express 4.14.1 version in my Nodejs application. I am also using body parser middleware for parsing form data but when I write console.log(req.body.variablename) I get undefined on the console.
my code is as follows
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser'); //parses information from POST
const request = require('request');
const mongodb = require('../model/mongodb.js');
const smtpTransport = require('../model/mailer.js');
const Agent = require('../model/agentmodel.js');
const config = require('../config.js');
const intent = require('../intents.js');
const ejs = require('ejs');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// use res.render to load up an ejs view file
router.get('/chat', function(req,res){
// res.sendFile(path.join(__dirname + '/html/' + '/index.html'));
res.render('pages/index', { heading: config.property.userheading});
});
// use res.render to load up an ejs view file
router.get('/', function(req,res){
// res.sendFile(path.join(__dirname + '/html/' + '/index.html'));
res.render('pages/helpdesk');
});
router.post('/createTicket', function(req,res){
console.log("create ticket is called from email support");
console.log(req.body);
console.log("and the details as follows ==>");
console.log("username is ==> "+req.body.userName);
console.log("message is ==>"+req.body.message);
var json = {
name : req.body.userName,
email : req.body.userEmail,
subject: 'Demo Subject',
message: req.body.message,
topicId : req.body.topicId,
};
var options = {
url: 'http://domainname/iprhelpdesk/upload/api/http.php/tickets.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key' : 'API-key'
},
json:json
};
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
console.log("response is ==>");
console.log(res);
}
else {
console.log("error is "+err+ " = and reponse code is ="+res.statusCode );
}
});
res.render('pages/message');
});
following is the output of the console
create ticket is called from email support {
'{"topicId":{"Id":12,"name":"Basic IPR Query"},"message":"i want to
know about ipr","userName":"Pawan
Patil","country":"IN","userEmail":"pawanpatil.rocks#gmail.com","contact":"09665714555"}':
'' } and the details as follows ==> username is ==> undefined message
is ==>undefined POST /createTicket 200 21.161 ms - 104 error is null =
and reponse code is =400
and this is what chrome is sending as a form data
{"topicId":{"Id":12,"name":"Basic IPR Query"},"message":"i want to
know about ipr","userName":"Jon
Snow","country":"IN","userEmail":"test#test.com","contact":"0123456789"}:
Request header is
Content-Type:application/x-www-form-urlencoded
everything seems to be perfect but still, I am getting
undefined
when I write console.log("username is ==> "+req.body.userName); in my code.
please help me out
Move those:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Before this:
app.use(app.router)
So your bodyParser need to be initialized before the router. I also have read that using this:
app.use(require('connect').bodyParser());
Insted of:
app.use(express.bodyParser());
May also fix the problem with undefined req.body
And one more thing to try is:
app.use(bodyParser.urlencoded({ extended: false}));
Set extended to be false instead of true
I have solved the problem from changing
Content-Type:application/x-www-form-urlencoded
header to the
Content-Type: application/json
I am building an API with Node.js, Express.js, and MongoDB. When I submit the form and use the req object in the route, the req.body object is empty.
req.body returns {} when I call the get_user function through the browser using postman at https://localhost:3000/users/0.
app.js:
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
bodyParser = require('body-parser');
var mongo_server = require('./server')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var routes = require('./routes/users')
routes(app);
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'});
});
app.listen(port);
mongo_server.mongo_connection
module.exports = app;
userController.js:
var mongoose = require('mongoose'),
user = mongoose.model('users');
exports.get_user = function(req, res) {
console.log(req.body.id);
user.findById(req.body.id, function(err, user) {
console.log(req.body);
if(err)
res.send(err);
res.json(user);
});
};
userRoutes.js:
module.exports = function(app) {
var users = require('../controllers/userController');
app.route('/users/:userid')
.get(users.get_user);
}
I think you're confusing request parameters and request bodies. A request body is when you send information with the request like a payload, such as in a POST request when you send JSON to the server to, for example, create a new user:
{
"username": "jd123",
"email": "jd#example.com",
"name": "John Doe"
}
But in your case, you're looking for parameters, things passed through the URL like you've set up:
/users/:userid
That allows you to navigate to with a GET request:
/users/0
And then you can get the 0 as a string from req.params.userid not req.body.id. Request parameters and bodies are different. Parameters are for navigating to a varying route such as a user profile page, where the URL varies and reflects which route you want to go to by a user's ID.
Bodies are used for the payload of a request such as POSTing, PATCHing, and PUTing, giving information on what to update or create on the server.