response object is undefined, of post method function - node.js

this is simple demo, making http post request and tries the log request object;
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var router = express.Router();
app.use(router)
app.use(bodyParser.json())
foo=(req, res)=>{
console.log(req.body)
res.send('Request Handled Here!')
}
router.route('/').post(foo)
app.listen(3300, '127.0.0.1', (req, res)=>{
console.log("Express listening!!!!")
});
I can see data "Request Handled Here" message but return data is undefined always in the console, I couldn't figure why "req" object is undefined out.
Edited: I am using postman to test api, content-type:application/json and there is {message:"hello world!"} dummy data in Body section
Edited2: it seems my only issue there is no "body" attribute in request context, it retrieves all req header but I just want to get posted data, many samples on net contains req.body section whats wrong here?

The problem in middleware declaration order. router must be added after body-parser:
var app = express()
var router = express.Router();
app.use(bodyParser.json());
app.use(router);

Related

Node.js - how to use a raw request body using Express

so I was making a RESTful API and I wanted to be able to receive raw json data (so I can use my api for mobile too), then from there save the data into my database (mongoDB).
But you see, there is this problem which I can't seem to fix and its that I'm not able to use the raw data as a json.
The code is simple
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});
app.post('/post', function(req, res){
res.send(parse.JSON(req.body));
//to convert it to json but this doesn't seem to work
})
PS. I'm using postman to send the request as raw format
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});
app.post('/post', function(req, res){
res.send(JSON.parse(req.body));
})
inside the res.send you have to use JSON.parse() instead of parse.JSON() which will throw an error as it is not correct
if you want to read more about JSON.parse you can visit mdn docs

Body parser is showing undefined in nodejs

The body parser is showing as undefined when i am sending the data through the url.
This is the url : http://localhost:3011/mybooking?email=example#example.com
Here is my code :
var bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('*',(req,res)=>
{
console.log(req.body)
console.log(req.body.email)
console.log(req.params.email)
})
const port = 3011
app.listen(port,(req,res)=>
{
console.log("App.js listening on the port "+port)
})
please do help me at your earliest.
my output is
App.js listening on the port 3011
{}
undefined
undefined
The variables passed in the URL are retrieved using req.query.
In your case to get the value of email, you need to retrieve using req.query.email.
req.body is used when the data is passed through the body (basically a post request)
req.params is used when data is passed using dynamic variables.
eg. http://localhost:3011/book/:id ---> req.params.id

app.post() method is not working in nodejs

I am new to MEAN Stack and have been developing some applications on Mean stack.But I am stuck with my app.post() method .The browser's console gives a 405 error saying that the method is not allowed.Please help me.
Here;s my code for server file in javascript
var app =express();
var mongoose =require('mongoose');
var bodyParser =require('body-parser');
var urlencodedparser=app.use(bodyParser.urlencoded({extended:false}));
var jsonParser = bodyParser.json()
app.get('/',function(request,response){
response.sendFile(__dirname+'/clients/views/index.html');
});
app.post('/api/meetups',jsonParser,function(req,res){
console.log(req.body);
});
var port=process.env.PORT || 3000;
app.listen(port,function(){
console.log('Listening to the server at port '+port);
});
Based on the Application.post() Express documentation, I think you probably want to change the first line of your post listener from:
app.post('/api/meetups',jsonParser,function(req,res){
console.log(req.body);
});
To this:
app.post('/api/meetups',function(req,res){
console.log(req.body);
});
I don't think it takes the additional parameter you specified related to JSON parsing. If you need to parse JSON you may want to look into using body-parser with middleware like this (which you would put ABOVE the post listener):
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Good luck!

Sending form data to an server using multer

I'm having some trouble sending form data to my Node.js server. I'm closely following the examples in the readme, but the result is either an empty object or undefined.
This is my server code:
var express = require('express')
var app = express()
var multer = require('multer')
var upload = multer()
app.post('/', upload.array(), function (req, res, next) {
console.log(req.body)
res.send("Hello from the server!")
})
app.listen(3000)
I'm testing this by running the following in the Chrome console:
var xml = new XMLHttpRequest()
xml.open("POST", "/")
var fd = new FormData()
fd.append("foo", "bar")
xml.setRequestHeader("content-type", "multipart/form-data; boundary=200")
xml.send(fd)
I don't know how to get the correct boundary for the setRequestHeader call, so I just put 200. When I send this, the server prints {}. It prints undefined without the setRequestHeader call. xml.responseText is the expected string Hello from the server!.

Why is request body undefined in one route?

I'm having some troubles trying to stablish a REST API with nodeJS and express. The following code defines two routes, "stores" and "user".
Surprisingly, the route to "/user" is working nice but when a request arrives to "/stores" the request body appears undefined. I've searched for a solution but nothing seems to work for me.
Both controllers have the same structure.
What am I doing wrong?
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
mongoose = require('mongoose');
// Connection to DB
mongoose.connect('mongodb://localhost/appDB', function(err, res) {
if(err) throw err;
console.log('Connected to Database');
});
// Middlewares
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
//Import models and controllers
var userModel=require("./models/user.js")(app,mongoose);
var storeModel=require("./models/store.js")(app,mongoose);
var usersController=require("./controllers/users.js");
var storesController=require("./controllers/stores.js");
//Router options
var router=express.Router();
router.route('/stores')
.get(storesController.getNearestStores);
router.route('/user')
.post(usersController.addUser);
app.use(router);
//Start server
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
Thank you very much.
P.S.:First time with nodejs and express(and even mongo)
This is because there is no body on a GET request in the http standard. Only POST and PUT.
What you want to do instead is use a query string
get
/stores?location=mystore
this way on your callback you have access to req.query
req.query
{
location: 'mystore'
}
HTTP GET with request body
This gave me the solution, get requests don't accept parameters under HTTP standard.

Resources