Body parser is showing undefined in nodejs - node.js

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

Related

node and express error "cannot GET /" even after I included app.get() in my server.js

I am trying to start my project via launching server.js but I am getting error:"cannot GET /"
even after I made an app.get() route in my server.js
I am using also "body-parser" as a middleware, and "cors"
server.js:
// Setup empty JS object to act as endpoint for all routes
const projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('views'));
const port = 8080;
app.use(express.static('dist'));
// Setup Server
const server=app.listen(port, ()=>{console.log(`running on localhost: ${port}`)});
app.get('/all', sendData);
function sendData (request, response) {
response.send(projectData);
};
// TODO-ROUTES!
app.post('/add', Info);
function Info(req, res) {
projectData['date'] = req.body.date;
projectData['temp'] = req.body.temp;
projectData['content'] = req.body.content;
res.send(projectData);
}
module.exports = server;
I made a POST request to /add and it works. Then I call GET /all and also work. The error cannot GET / is because you are requesting an endpoint that not exists.
Just add a dummy data to your Fn() if you want to see some output on GET request wihtout making any post request
Here is my solution
app.get('/', (req, res) => {
res.redirect('/all');
})
we need this because you do not have any root URL set, so we set the root URL to redirect to /all
2nd step then we add a dummy data in the projectData
var projectData = {
date = new Date().getDate();,
temp = 10,
content="This is Test Content"
}
This way when you call 'http://localhost:8080/' you shall get redirected to http://localhost:8080/all and instead of empty {} you shall see the dummy data.

How to use body request express

I want to access to the body to my request but he is empty. I use a body-Parser but I don't know why I haven't data in my body.
import express from 'express';
import * as bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const port = 3000;
app.post('/', (request, response) => {
response.send(request.body);
});
app.listen(port, () => {
console.log(`you can run the server on http://localhost:${ port }`);
});
result:
{}
for my request I use postman
so I don't understand, I read other topic or forums and he this is the same code.
body-parser uses the Content-Type header to determine how the body will be parsed. My immediate suspicion (because I've done the same thing before) is that you may not be passing the Content-Type header - for example, if you are trying to use JSON, you need to be sending Content-Type: application/json on your POST request.

response object is undefined, of post method function

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);

Assigning req.body to a variable

I'm trying to post data from a leaflet layer and then run it through express and return an array using a third-party module.
If I stipulate the id needed in the call like this
forecast = msw.forecast(1)
it works fine. When I try to use the spot_id coming from the post request it gives me this:
TypeError: Cannot use 'in' operator to search for 'units' in 1
Here's the what I'm using on my node.js server. Any help would be really appreciated.
var express = require('express');
var app = express();
var msw = require('msw-api');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
msw.set({ apiKey: 'my-api-key' , units: 'UK' });
app.post('/', function(req, res){
spot_id = req.body.spot_id
forecast = msw.forecast(spot_id).then(function (forecast) {
res.send(forecast)
});
});
app.listen(3000, function () {
console.log('Listening on port 3000!');
});
As discussed in the comments the value of the req.body.spot_id is string by default and the msw.forecast(spot_id) requires an integer as its argument hence the error.
All you have to do is parse the spot_id to integer as shown below:
var spot_id = parseInt(req.body.spot_id)
Before feeding it to forecast as argument.

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