req.body undefined in MEAN stack - node.js

I'm working on my first mean stack application and running in to a problem. I have a Blog model and I'm trying to assign the properties from the req object but its undefinded. When I do a console log of the req.body it looks like this:
{ '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''}
but when I log the values out individually like console.log(req.body.title) its undefined. In my server.js I've included body parser and made sure the route is after incorporating body parser. So at this point I'm not sure why it would be undefined any help is appreciated.
Here is the post for the blog:
createAuthenticationHeaders() {
this.authService.loadToken();
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
authorization: this.authService.authToken
})
};
}
newBlog(blog) {
this.createAuthenticationHeaders(); // Create headers
return this.http.post(this.domain + 'blogs/newBlog', blog,
this.httpOptions);
}
This is the payload
Thanks
Here is that file
const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose');
const config = require('./config/database');
const path = require('path');
const authentication = require('./routes/authentication')(router);
const blogs = require('./routes/blogs')(router);
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 8080;
mongoose.connect(config.uri, err => {
if (err) {
console.log('Connection error db ', err);
} else {
console.log('Connected to db ', config.db);
}
});
app.use(
cors({
origin: 'http://localhost:4200'
})
);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client/dist/'));
app.use('/authentication', authentication);
app.use('/blogs', blogs);
app.get('*', (req, res) => res.sendFile(__dirname +
'/client/dist/index.html'));
app.listen(port, () => console.log(`App listening on port ${port}`));

When I do a console log of the req.body it looks like this:
{ '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''}
You're posting a JSON, which has another JSON as property, therefore req.body.title is undefined. Check your client side, because you're posting the JSON wrong.
// This is what you say you're getting
const bad = { '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''};
console.log(bad);
console.log(bad.title);
// This is what you should post
const good = {"title":"some title", "body":"some body", "createdBy":"created By"};
console.log(good);
console.log(good.title);
Update
You're sending form data, instead of a JSON payload.
use: 'Content-Type': 'application/json' instead of 'Content-Type': 'application/x-www-form-urlencoded'

Related

Express JS - post method - req.body is getting undefined even I use app.use(express.json())

my code is like this -
const express = require("express");
const path = require("path");
const { open } = require("sqlite");
const sqlite3 = require("sqlite3");
const dbPath = path.join(__dirname, "moviesData.db");
const app = express();
app.use(express.json());
app.use(express.urlencoded({
extended: true
}))
let database = null;
const initializeDBAndServer = async () => {
try {
database = await open({
filename: dbPath,
driver: sqlite3.Database,
})
app.listen(5353, () => {
console.log(`server is running at http://localhost:5353/`)
})
} catch (error) {
console.log(`error: ${error.message}`);
process.exit(1)
}
}
initializeDBAndServer();
app.post("/myId", async (req, res) => {
const { id } = req.body;
console.log(`requested Id is ${id}`);
res.send(`requested Id id ${id}`);
})
my request is -
POST http://localhost:5353/myId/
Content-Type: "application/json"
{
"id": 123456
}
And the console and response is coming the same
requested Id is undefined
I have used - app.use(express.json()). It is not working.
And also installed body-parser and also tried. It also not worked.
So, please help me out by giving the correct code.
The Content-Type in your request is incorrect, it should be application/json, not "application/json":
Content-Type: application/json

express server returns 405 on routes in production

Im building an express instance for the first time and ive run into an issue where everything works locally, but when deployed sending a post request to the route responds:
Failed to load resource: the server responded with a status of 405
(Not Allowed)
Ive included the relevant code below:
server/index.js
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
const routes = require('./routes')(express)
require('./db')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(process.env.PORT || 8080);
app.use('/', routes);
routes/index.js
var mongoose = require("mongoose");
const randomId = require('random-id');
const Submissions = require('../api/Submissions')
// routes/index.js
module.exports = (express) => {
// Create express Router
var router = express.Router();
// add routes
router.route('/submission')
.post((req, res) => {
let newSubmission = new Submissions(req.body);
newSubmission._id = randomId(17, 'aA0');
// Save the new model instance, passing a callback
newSubmission.save(function(err,response) {
if (err) {
console.log(err)
} else {
res.setHeader('Content-Type', 'application/json');
res.json({'success':true})
}
// saved!
})
});
return router;
}
client.js
let submission = {
name: this.state.newSubmission.name.trim(),
body: this.state.newSubmission.body.trim(),
email: this.state.newSubmission.email.trim(),
};
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(submission),
};
fetch("/submission", requestOptions)
.then((response) =>
response.json().then((data) => ({
data: data,
status: response.status,
}))
)
.then((res) => {
if (!res.data.success) {
notifier.warning('Failed to submit');
} else {
notifier.success('Submission successful');
}
});

Can Not POST NodeJS Express

I was trying to make an axios post request to an express server and I receive that Error: Request failed with status code 404 at createError. Postman says Can Not POST. I don't know what could be wrong, i'm new in all this, so all the help it's good, thanks.
Axios and Express server are from 2 different link. They are google cloud function.
Thanks for the help
Axios Post Request :
exports.notification = (req, res) => {
var axios = require('axios');
var https = require('https');
var bodyParser = require('body-parser');
var config = {
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Type' : 'text/html',
'Content-Type' : 'application/json' }
};
var info = {
ids:[req.body.id,req.body.id1],
type: req.body.type,
event: req.body.action,
subscription_id: req.body.subid,
secret_field_1:null,
secret_field_2:null,
updated_attributes:{
field_name:[req.body.oname,req.body.nname]}
};
var myJSON = JSON.stringify(info);
return axios.post('https://us-central1-copper-mock.cloudfunctions.net/api/notification-example', myJSON)
.then((result) => {
console.log("DONE",result);
})
.catch((err) => {
console.log("ERROR",err);
console.log("Error response:");
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
})
};
Express Server
const express = require ('express');
const https = require ('https');
const bodyParser = require ('body-parser');
const app = express();
const port = 8080;
// ROUTES
var router = express.Router(); // get an instance of router
router.use(function(req, res, next) { // route middleware that will happen on every request
console.log(req.method, req.url); // log each request to the console
next(); // continue doing what we were doing and go to the route
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/',require ('./Routers/API/home'));
app.use('/leads',require ('./Routers/API/leads'));
app.use('/people',require ('./Routers/API/people'));
app.use('/companies',require ('./Routers/API/companies'));
app.use('/opportunities',require ('./Routers/API/opportunities'));
app.use('/projects',require ('./Routers/API/projects'));
app.use('/tasks',require ('./Routers/API/tasks'));
app.use('/activities',require ('./Routers/API/activities'));
app.use('/notification-example',require ('./Routers/API/notification_example'));
app.use('/', router); // apply the routes to our application
// START THE SERVER
// ==============================================
app.listen(port);
console.log('Listening ' + port);
module.exports={
app
};
Notification Route
const express = require('express');
const router = express.Router();
//const notification_example = require('../../Notification');
router.get('/', function(req, res) {
console.log('DATA',JSON.parse(res.data));
console.log('BODY',JSON.parse(res.body));
});
module.exports = router;

Express JS is receiving an empty req.body from ReactJS

I am currently having a problem with React and Express JS form submit function. It seems like my nodeJS running on port 5000 is receiving an empty object from my ReactJS running on port 8080 using fetch method.
React : Contact.js
handleSubmit(e)
{
e.preventDefault();
var data = {
name: this.state.name,
contact: this.state.contact,
email: this.state.email,
message: this.state.message,
}
var url = 'http://localhost:5000/api/insertUsers';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
mode: 'no-cors',
body: JSON.stringify(data),
})
.catch((error) => {
console.log(error);
});
}
NodeJS : server.js
const express = require('express');
const { Client } = require('pg');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/api/insertUsers', function(req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
});
app.listen(5000, () => {
console.log('listening on port 5000');
});
Change the order of bodyparser middleware like this.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
You are sending a request with the content-type of 'application/json' but express is expecting a content-type of 'text/json'. Usually, when req.body is empty content-type is the first suspect you should be looking at.
I am ashamed that I struggled with this for hours. I still haven't gotten it to work with file uploads.
But I did get it to work with a normal form by encoding JSON and sending that along with axios, instead of fetch
My js code
var data = {
id: this.state.id,
}
console.log('data',data)
var bodyFormData = new FormData();
bodyFormData.set('id', this.state.id);
var url = ' http://localhost:3000/get-image-by-id';
console.log("bodyFormData: ", bodyFormData);
axios({
method: 'post',
url: url,
data: data,
// headers: {'Content-Type': 'multipart/form-data' }
headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Form Code
<form method="POST" onSubmit={this.handleSubmit} >
<label>
Transaction ID
<input
type="text"
name="id"
value={this.state.id}
onChange={this.handleInputChange}
/>
</label>
<button type="submit">Submit</button>
</form>
```
EDIT
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors'
}).then((result)=>{
console.log("output" + result.json());
})
.catch((error) => {
console.log(error);
});
EDIT 2
for backend, install cors and add the following lines before route.
var cors = require('cors')
app.use(cors())
EDIT 3
perform npm install morgan then copy these lines inside the code
var morgan = require('morgan');
app.use(morgan('dev'));
I didn't look at your code close enough. My bad
app.post('/api/insertUsers', function(req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
});
Should be
app.post('/api/insertUsers', function(req, res) {
res.json(req.body)
});
try using axios instead of fetch
I rewrote ur code like this and it works perfectly
server
const express = require('express');
const { Client } = require('pg');
const bodyParser = require('body-parser');
const app = express();
const cors = require("cors");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/insertUsers', function(req, res) {
// console.log(req);
console.log(req.body);
res.send(req.body);
});
app.listen(3001, () => {
console.log('listening on port 3001');
});
react (ensure you have axios installed)
handleSubmit(e){
e.preventDefault();
var data = {
name: "zadiki",
contact: "0702002109",
email: "zadiki",
message: "test",
}
console.log("wow");
var url = ' http://localhost:3001/api/insertUsers';
axios.post(url,data)
.then(response=>console.log(response))
.catch(e=>console.log(e))
}
Hello I ended up getting mine working after I ran into the same problem.
I noticed your react code has "mode: 'no-cors'," that was causing problems with mine so I removed it.
-------- Below is my handle submit code for React ------------
const handleSubmit = (event) => {
event.preventDefault();
const url = "http://localhost:3001/register"
const options = {
method: "POST",
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json"
}
}
fetch(url, options)
.then(res => res.json())
.then(res => console.log(res))
}
I used express.json instead of bodyParser. You also had a typo in your express code, it should say res.send instead of res.end
--------- Below is my Node Express Code -----------
const express = require('express');
const app = express();
const cors = require('cors');
const multer = require('multer');
// Middlewares
app.use(cors({ origin: 'http://localhost:3000', }))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(multer().array());
app.post('/register',(req, res) => {
console.log(req.body)
res.status(200)
.json({status:"Success", data:{body: req.body })
});
app.listen(3001, () => console.log(`Running on 3001`))
I was able to send form data using postman and react using the code above. Feel free to change it to accommodate your needs.

req.body.variablename is undefined in express with body-parser middleware

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

Resources