The body of my Angular post request is empty - javascript

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

Related

Cant render EJS file as a Response to POST request

I've just started learning Express and Servers.
Problem
Just wanted to load another EJS page onto my localhost:4000/ path as a response after a POST request has been made for a form.
However, although I do get the response of the EJS page with the data from the req.body in the form from the client-side. I can't seem to get the page to load on the browser.
Any ideas? pls help
Express.js Server
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let path = require('path');
let fs = require('fs');
var urlencodedParser = bodyParser.urlencoded({extended:true});
app.use(express.json());
app.set('view engine', 'ejs');
app.use('/', express.static(__dirname + '/views'));
app.use('/', express.static(__dirname + '/views/partial'));
//Handling the GET request with the render of EJS file "index"
app.get('/', (req, res)=> {
res.render('index');
});
//Handling the POST request from the client, and sending the EJS file "createAccount" as a response
app.post('/', urlencodedParser, (req, res) => {
res.set('cache-control', 'max-age=0; private; no-cache');
res.render('createAccount', {data:req.body}); //
});
app.listen(4000, ()=>{
console.log('Port 4000 has been called');
});
EDIT:
I've included the JS file which I am using to make the POST request below.
document.querySelector('#btn').addEventListener('click', Master);
async function Master(){
console.log("Button clicked")
const username = document.querySelector("#username").value;
const password = document.querySelector("#password").value;
let results = {
"username": username,
"password": password
};
console.log(results);
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(results)
};
const post = await fetch('/', options);
};
I don't know if this is a correct question lol but is it ok to have the same "/" in get and post request? Why not put something in it.
app.post("/create")
then also change this
const post = await fetch('/create', options);

express POST req.body parser is empty

I saw similar issues on Stack Overflow and found solution to use of:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
But while printing log req.body is blank.
app.js contents:
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
// Define the port to run on
app.set('port', 8888);
app.use(express.static(path.join(__dirname, '/webapp/public')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/getsolution', function (req, res) {
console.log("request body is",req.body); //----req.body is blank here
});
Post request code from angular is as below
var parameters = JSON.stringify({ "urlPath": $location.path()});
$http.post('http://localhost:8888/getsolution/', parameters)
.then(function (response) {
if (response.data == "") {
$window.location.href = 'http://localhost:8888/';
} else {
$scope.puzzle = response.data;
$scope.puzzleSolution = response.data.solution;
}
}).catch(function onError(response) {
$window.location.href = 'http://localhost:8888/';
});
Log printing on console is
request body is {}
When using with below snippet it is not working
var app = angular.module('puzzleappsolution', [], function ($locationProvider) {
$locationProvider.html5Mode(true);
});//----->It is now working
But when using below it is working
var app = angular.module('puzzleappsolution', []);
Add Content-Type header to your request in angular:
$http.post('http://localhost:8888/getsolution/', parameters, {
headers: {
'Content-Type': 'application/json'
}
})

Express keeps getting request.body as undefined JSON object

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

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

Parsing POST data with body-parser in Node.js app

I am trying to build a simple Node.js app which will parse data passed to it as POST requests from my AngularJS app. Below is the code used in my AngularJS app and my Node.js app. Problem I am facing is that I've searched the web trying to find how to parse (data and header) information passed in POST requests but failed to find any example, so any help with an example of parsing (data and header) passed in POST requests will help me a lot. Thanks.
Note: I am using express 4.1.2, body-parser 1.8.0.
Node app:
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.post('/', function (req, res) {
console.log(req.body);
res.send(200);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
POST request code
var deferred = $q.defer();
var dataObj = {};
dataObj.name = 'Chan';
dataObj.email_address = 'email#domain.com';
var myToken = '1234567890';
$http({ method:'POST',
url: '/',
data: dataObj,
headers: { 'Token' : myToken
}
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data,status,headers,config){
deferred.reject(status);
});
return deferred.promise;
If you're setting data to a plain js object, angular is interpreting that as a urlencoded form with the various keys and values in that object.
So there's two possible fixes here. One is to add something like app.use(bodyParser.urlencoded({ extended: false })); after app.use(bodyParser.json());
The second possible fix is to change your $http call to post JSON instead of urlencoded data. For that, change data: dataObj, to data: JSON.stringify(dataObj), and add 'Content-Type': 'application/json' to your headers so that it looks like this:
headers: {
'Token' : myToken,
'Content-Type': 'application/json'
}

Categories