Express keeps getting request.body as undefined JSON object - javascript

I am making an Ajax request that looks like this:
$.ajax({
url: '/gen',
type: 'POST',
data: JSON.stringify({'one': 1, 'two':2}),
success: function(data) {console.log(this)}
});
and my express portion looks like this:
var express = require('express');
var app = express();
var router = express.Router();
app.set('port', (process.env.PORT || 5000));
router.post('/gen', function(req, res) {
console.log(req.body);
});
this always outputs undefined in the console.
How can I change this around to make the req.body, or any part of the req, contain the information I am trying to send over to the express portion of the code.

You need to use the body parser.
var bodyParser = require('body-parser')
app.use(bodyParser.json());
See:
https://github.com/expressjs/body-parser
You may also need to add:
contentType: 'application/json',
in your .ajax() options.

To use use req.body you have to use the bodyParser middleware, import it like this:
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
router.post('/gen', function(req, res) {
console.log(req.body);
});

Related

Node.js express - body of POST request is always empty

I am trying to read the body of POST request using Express in Node.JS framework. I send a HTTP POST request using HTML form. I detected a POST request on WireShark with the following data:
This shows that the request is sent successfully. I expected JSON format, which is the one that Express successfully parsed for me, but this format just doesn't seem to work no matter what I tried. My current implementation goes like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json()
//Import static files
app.use(express.static('../public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', jsonParser, (req, res) => {
console.log(req.body);
res.send(200);
});
app.listen(port, () => console.log("Server started"));
No matter what I try from other posts, it still does not seem to return me any data.
Does anyone have an idea how to fix this problem?
Why to you use 'jsonParser' in the app route? Try something like:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/post-test', (req, res) => {
console.log('Got body:', req.body);
res.sendStatus(200);
});

returning undefined for get request

I have been doing a project in URL shortening and i am getting an undefined as a result to get request.
Also i get a blank page too as result,but according to my knowledge everything is ok,i can't figure out what is the mistake
Here's my code(please check the app.get section)
'use strict';
var bodyParser = require('body-parser')
var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var http = require("http");
var cors = require('cors');
const dns = require('dns');
var app = express();
// Basic Configuration
var port = process.env.PORT || 3000;
/** this project needs a db !! **/
// mongoose.connect(process.env.DB_URI);
app.use(cors());
/** this project needs to parse POST bodies **/
// you should mount the body-parser here
app.use('/public', express.static(process.cwd() + '/public'));
app.get('/', function(req, res){
res.sendFile(process.cwd() + '/views/index.html');
});
// your first API endpoint...
app.get("/api/hello", function (req, res) {
res.json({greeting: 'hello API'});
});
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
var saveSchema = new mongoose.Schema({
name: String,
url: Number,
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
/** 3) Create and Save a Person */
var SaveData = mongoose.model('Save', saveSchema);
//**Here's the start of my problem,i think**
app.get("/api/shorturl/:id1",function(req,res){
SaveData.find({url:1},function(err,data){ console.log(data.name)//**i am getting undefined for this in console**
res.json(data.name);})
});
app.post("/api/shorturl/new",(req,res)=>{
var body=req.body.url;
dns.lookup(body,(err,data)=>{
var new2= new SaveData({name:body,url:1});
new2.save((err,data)=>{res.json(new2);});
})
});
app.listen(port, function () {
console.log('Node.js listening ...');
});
I checked my DB whether the schema data is inputted or not, it is getting inside DB, so retrieval makes the problem I think.
mongoose.model.prototype.find returns an array of objects found. If you type Array.prototype.name in a console somewhere, you'll get undefined. Instead, use mongoose.model.prototype.findOne.
Your enviorment variables are working? I notice you're not using dotenv module or something like that to configure your process.env.

The body of my Angular post request is empty

So the body of my Angular post request is empty on my server. The post request from my client application is:
var data = {
Stime: '+this.Stime+',
Etime: '+this.Etime+',
eAMPM: '+this.eAMPM+',
sAMPM: '+this.sAMPM+',
id: '+this.id+',
activity: '+this.activity+',
auto_insert: '+this.auto_insert+',
yearmonthday: '+this.yearmonthday+',
color1: '+this.c+'
}
this.$http({
method: 'POST',
url: 'http://localhost:3000/operation',
data: JSON.stringify(data)
})
before I tried using this post request I just had a very long query string and this passed the data just fine. But I am cleaning up my code now and this way isnt working.
On my server I have:
app.post('/operation', function(req,res){
console.log(req.body); //prints {}
res.send("inserted");
});
Also on the server side I have
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
multer = require('multer'),
jsonParser = bodyParser.json()
app.use(jsonParser)
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Inside app.post(...) {} you need to wait for data to become available like this:
var body = '';
req.on('data',function(data) { body += data; });
req.on('end', function(data) {
req.body = JSON.parse(body);
conosle.log(request.body);
});

Sending json with $.post in express/node

This is my app.js file:
var express = require('express');
var app = express();
var path = require('path');
var $ = require('jquery');
var nodemailer = require('nodemailer');
app.use('/static', express.static(path.join(__dirname, 'static')));
app.get('/', function(req, res) {
res.sendFile('./views/index.html', {"root": __dirname});
});
app.post('/contact/', function(req, res){
console.log(req.body);
});
and my post request from another file, which is called when a form is submitted:
$('form').submit(function(e){
e.preventDefault();
var content = $('#message').val();
var email = $('#EmailInput').val();
var reason = $('#reason').val();
$.post('/contact', { 'content': content, 'email': email, 'reason': reason }, function(data){
console.log(data);
});
})
However, whenever the form is submitted, the post request is successful, it's just no data has been passed.
req and req.body both return undefined. I can't figure out why.
you need the body parser to populate the body property of the request object
npm install body-parser
then include
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
documentation for your particular use case and tweaking may be found here
edit: be sure to include this BEFORE your route handlers are declared

nodejs express 4.0 post json object

I am trying to parse the json object sent in the request and echo out the data being sent
Here is my post request
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
name:"Bob"
}),
// processData: false, // this is optional
dataType: 'json'
});
Here is how I am trying to access the object parameters
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', router);
app.listen(8010);
router.post('/addUser', function(req, res){
console.log(req.body);
});
I think you need :
router.post('/addUser', function(req, res){
console.log(req.body.name);
});
EDIT
After testing it, you also miss these two lines (or you didn't include them on purpose) :
app.use(router); //You need to register your rooter as a middleware
app.listen(1234); //Your port of choice
The key here is the fact that you use the middleware 'body-parser'.
What it does is simple, it parses the data and creates a body object as a parameter of your request.
Therefore, the name parameter you're looking for will be found in : req.body.name and not in param
Quote from the github page :
req.body
A new body object containing the parsed data is populated on the request object after the middleware.

Categories