express POST req.body parser is empty - javascript

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

Related

Problem with sending data from Angular to Express

I'm trying to post data from Angular to Express.js
This is my function connected to the button (TypeScript):
upload(): void {
const nameFromId = document.getElementById('taskName') as HTMLInputElement;
this.taskName = nameFromId.value;
const testData = [
{
task: this.taskName,
selectedType: this.selectedType,
selectedSubject: this.selectedSubject
}
];
const body = JSON.stringify(testData);
this.http.post('/api/upload', body)
.subscribe();
"body" is not null
This is express:
const express = require('express');
const path = require('path');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/api/upload', (req, res) => {
let task = req.body.task;
let selectedType = req.body.selectedType;
let selectedSubject = req.body.selectedSubject;
console.log("task: " + task);
console.log("type: " + selectedType);
console.log("subject: " + selectedSubject);
console.log("server: " + req.body);
res.end("yes");
})
app.use(express.static(__dirname + '/dist/al'));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname + '/dist/al/index.html'));
});
app.listen(process.env.PORT || port);
And this is what I get as a mistake:
mistake from console
If I put extra options to my "post method" from Angular and write something like:
this.http.post('/api/upload', body, {responseType: 'text'})
.subscribe();
After adding responseType: 'text' this mistake is no longer exists, but when it comes to console.log all data, that I posted to express, undefined:
Express console.log
What am I doing wrong?
You are sending a string as http request body.
Don't use JSON.stringify, try sending object as is.
const testData = [
{
task: this.taskName,
selectedType: this.selectedType,
selectedSubject: this.selectedSubject
}
];
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
}
this.http.post('/api/upload', testData, httpOptions)
.subscribe();
Also add this line to server:
app.use(bodyParser.json());
Finally:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());

Data undefined at Node.js from AngularJS POST request

I am attempting to send a fairly simple POST request to my server using AngularJS. The request goes through and hits my controller on the back end, but for some reason req.data is showing up as undefined.
Front End Controller:
function CardDirectiveController($http, $scope) {
var self = this;
self.addToFavorites = function() {
let card = {
id: $scope.$id,
attack : $scope.attack,
cost: $scope.cost,
img: $scope.img,
name: $scope.name,
class: $scope.class,
rarity: $scope.rarity,
type: $scope.type
}
return $http({
method: 'POST',
url: '/card',
data: card
})
};
}
angular.module('cardDirective').controller('CardDirectiveController', CardDirectiveController);
Server
'use strict';
let express = require('express'),
path = require('path'),
router = require('./routes/sampleRouter'),
cardRouter = require('./routes/cardRouter');
let app = express();
// Serve any requests for static files (like index.html)
app.use(express.static(path.join(__dirname + '/public/')));
// Use any routing rules found in the router file
app.use('/', router);
app.use('/card', cardRouter)
app.listen(PORT, function() {
console.log('Application live and running on port: ' + PORT);
});
Router:
'use strict';
let express = require('express'),
cardController = require('./../controllers/cardController');
let router = express.Router();
router.route('/').post(cardController.postCard);
router.route('/:cardName').get(cardController.showCards);
module.exports = router;
Back End Controller
'use strict';
let cardController = {
showCards: showCards,
postCard: postCard
};
module.exports = cardController
function showCards(req, res) {
console.log('showCards ', req.params.cardName);
res.end()
}
function postCard(req, res) {
console.log('postCard ', req.url, req.method, req.data)
res.end()
}
The response I am getting in the console from making this request is postCard / POST undefined. Console logging the card object returns the expected result. I feel like I must be missing something obvious, but I've been stuck for a while now.
You need to use bodyParser middleware to parse request body.
Install the body-parser module:
$ npm install body-parser
Configure it in app.js :
var bodyParser = require('body-parser');
// parse application/json
app.use(bodyParser.json());
In your controller use req.body instead of req.data:
function postCard(req, res) {
console.log('postCard ', req.url, req.method, req.body);
res.end();
}
Please use body-parser in your app.js file.
Change your server.js file to following code
'use strict';
let express = require('express'),
path = require('path'),
router = require('./routes/sampleRouter'),
cardRouter = require('./routes/cardRouter'),
bodyParser = require('body-parser');
let app = express();
// Serve any requests for static files (like index.html)
app.use(express.static(path.join(__dirname + '/public/')));
// parse application/json
app.use(bodyParser.json());
// Use any routing rules found in the router file
app.use('/', router);
app.use('/card', cardRouter)
app.listen(PORT, function() {
console.log('Application live and running on port: ' + PORT);
});

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

How to read array of json objects on MEAN Stack (with MySql instead of Mongo)

It happens that we are working on a web page that uses a list of users (for example) that we got from a MySql on the form of an array of JSON objects, it worked (we tested it with console.log() )... but that was until I activated Angularjs on the front-end.
The code that I used on the respective files are as follow...
controller.js (angular module):
var app = angular.module("App",[]);
app.controller("AppController",function($scope, $http){
$scope.listofusers = [];
$http.get('/api/users')
.success(function(data){
$scope.listofusers = data;
console.log(data);
})
.error(function(data){
console.log("Error: " + data);
});
api.js:
router.route('/users')
.get(function(request, response) {
usuariosModel.getUsuarios(function(error, data) {
data = JSON.stringify(data);
data = JSON.parse(data);
console.log(data);
response.status(200).json(data);
});
})
.post(function(request, response) {
var datosUsuario = {
username: request.body.username,
password: request.body.password,
email: request.body.email,
permiso: request.body.permiso
};
usuariosModel.insertUsuario(datosUsuario, function(error, data) {
console.log(data);
if (data) {
response.status(200).json({
"Mensaje": "Insertado"
});
} else {
response.status(500).json({
"Mensaje": "Error"
});
}
});
});
routes.js:
var express = require('express');
var app = express();
var path = require('path');
app.get('/api/usuarios', function(req, res) {
res.render('readusers.html');
//res.sendFile(path.resolve('./views/readusers.html'));
//res.sendFile(path.join(__dirname, '../', 'views', 'readusers.html'));
});
app.get('/api/usuarios', function(req, res) {
res.render('index_users')
});
app.put('/api/usuario/:username', function(req, res) {
res.render('edit');
});
module.exports = app;
server.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var mysql = require('mysql');
var config = require("./models/config.js");
var fs = require('fs'); // manejo filesync
var methodOverride = require("method-override");
var connection = mysql.createConnection(config);
connection.connect(function(error) {
if (error) {
console.error('Error connecting: ' + error.stack);
return;
}
console.log('Connected to server with thread ID ' + connection.threadId);
});
// DB structure
sql_structure = fs.readFileSync('./models/bd.sql').toString();
connection.query(sql_structure, function(error, rows) {
if (error) throw error;
console.log('Base de datos: Estructura completada');
});
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
//app.set("view engine", "html");
//app.use(express.static(__dirname + '/views'));
//app.engine('html', require('ejs').renderFile);
app.use(methodOverride("_method"));
app.use('/', require('./router/routes'));
app.use(express.static(__dirname + '/views'));
//Express
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
//Routes
app.use('/api', require('./router/api'));
app.listen(3000, function() {
console.log("Server on");
});
Hope someone finds what is missing, we have looked through a lot of tutorials and still can't find the mistake.

Node express request call inside get

I'm trying to use nodejs as a layer between my public website and a server on the inside of our network.
I'm using express.js to create a simple REST api. The API endpoint should trigger a request call to a webservice, and return the result.
But the request call inside my .get() function doesn't do anything.
I want to return the result from the nested call to be returned.
Code:
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is workiung on IISNode')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
res.send('Customer ID: ' + req.params.customerId + ' Invoice ID: '+ req.params.invoiceId)
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request('http://www.google.com', function (error, response, body) {
res.send(body);
})
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
Any suggestions?
You can write in this way
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is working')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request(url, function (error, response, body) {
var data={
body:body,
customerID:req.params.customerId,
invoiceID:req.params.invoiceId
};
res.send(data);
});
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
Please find the snippet I am using. Hope this helps for you as well.
var body="";
function callyourservice(customerId,invoiceId,callback) {
var options = {
uri : url + 'costumer=:customerId&invoice=:invoiceId',
method : 'GET'
}
request(options, function (error, response, body) {
console.log(response);
if (!error && response.statusCode == 200) {
res = body;
}
else {
res = 'Not Found';
}
callback(res);
});
}
callyourservice("customerId value","invoiceId value", function(resp){
body=JSON.stringify(resp);;
});
You can write callyourservice inside a get method from client like
app.get('/'){
}
You can try doing it the node way using pipe
var http = require('http');
http.createServer(function(request, response) {
var proxy = http.createClient(9000, 'localhost')
var proxyRequest = proxy.request(request.method, request.url, request.headers);
proxyRequest.on('response', function (proxyResponse) {
proxyResponse.pipe(response);
});
request.pipe(proxyRequest);
}).listen(8080);
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to port 9000!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
You can find the reference here

Categories