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
Related
I have 2 node js apps one sending a post request as follows:
request.post({
url: url,
headers: {"content-type": "application/json"},
json: {a:1,b:2}
},
function (error, response, body) {
//..
}
);
and the other is trying to handle it with express and body-parser:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/verify', (req, res,cb = (err, res) => {}) => {
var data = req.body; //returns empty json!
// ..
}
the problem is that at the receiving end I can't retrieve the json data I'm looking for. Does any body know what I'm missing?
Adding this to your server side code should work:
app.use(bodyParser.json())
I'm trying to use body-parse version 1.18.3 with express to parse a json post. In app.js I've included it like so
app.js
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
...
//App setup
var app = express();
// create application/json parser
var jsonParser = bodyParser.json()
app.set('trust proxy', 1) // trust first proxy
// Use the session middleware
app.use(session({ secret: 'secretletters', cookie: {}}))
app.post('/', jsonParser, function (req, res) {
console.log(req.body);
if (req.session.username) {
} else {
}
res.send({'status': 'ok'})
});
and in my script on the frontend send a username back to it
$('.login-btn').click(function() {
let username = $('.username').val();
if (username == '') {
$('.login-error').removeClass('hidden');
return null;
}
//if passed hide error
$('.login-error').addClass('hidden');
var data = {
'username': username
}
$.ajax({
url: "/",
type: "POST",
dataType: 'json',
data: JSON.stringify(data),
success: function(response){
},
error: function(xhr){
},
});
/* End Ajax Call */
});
It send the username successfully, here's a screenshot of the results of the post request from the network tools
the bug is when on console.log(req.body); on app.post I get back and empty {} dict
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'
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 */
I am trying to get data from server and show it on web page but
I am getting a error at end of file
response.end(body);
TypeError: undefined is not a function
i don't get what the error is please help
My Nodejs Code
var express=require("express");
var app=express();
var request = require('request');
var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/service',function(req,res){
var id = req.query.name;
console.log('hi');
console.log(id);
request.post({
headers: {
//set header if needed
},
url : 'http://example.com:8080/rest/api/2/issue/id',
json : {
userName:'username',
password:'password'
}
},
function(error, response, body){
if(error) {
console.log(error);
} else {
response.end(body);
}
});
});
console.log('running');
app.listen(8082);
You want to use the res variable, which is the response object passed into your Express request handler:
res.end(body);
response is an object passed by the request library that you're using, which is a different thing.