Node Js get post data as json key - angularjs

NodeJS File server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var moment = require('moment');
var http = require('http');
var jwt = require('jsonwebtoken');
var config = require('./config');
var User = require('./app/models/user');
var port = process.env.PORT || 8080;
mongoose.connect(config.database);
app.set('superSecret', config.secret);
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.post('/onboardAuthentication', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
res.setHeader('contentType', 'application/x-www-form-urlencoded;charset=utf-8;');
res.json(req.body);
});
var server = http.createServer(app);
server.listen(port);
console.log('Magic happens at http://localhost:' + port);
Angular API Hit Code where Front side API hit
var serviceRoot='http://localhost:8080/onboardAuthentication';
var deferred=$q.defer();
var req = {
method: 'POST',
url: serviceRoot,
data: { key: 'value' },
contentType: 'application/x-www-form-urlencoded;charset=utf-8;'
};
$http(req).then(goodResponse,badResponse);
return deferred.promise;
function goodResponse(response)
{
console.log("Good response");
console.log(response);
}
function badResponse(response)
{
console.log("Bad response");
console.log(response.data);
}
It print result in this formate, it make post data as key and value is blank, but i want to access post data in json format using body-parsar node js.
{"key":"value"}: ""

If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work,
by default angular will send application/json to the server.
var req = {
method: 'POST',
url: serviceRoot,
data: { key: 'value' },
// comment this line, you don't need it
//contentType: 'application/x-www-form-urlencoded;charset=utf-8;'
};

Related

PUT/ update operation fails in $resource AngularJS client in rest based app (mongoose insert / update issue).

I am new to MEAN applications.Here I have a REST based sample application using node-restful library in which I can perform operations(get,save,delete) except 'put'. However 'put' operation works well on rest clients (advanced REST, postman) but not on angular client.
mongoose Model
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var productSchema = new mongoose.Schema({
name: String,
college: String,
age: Number
});
// Return model
module.exports = restful.model('Products', productSchema);
Node-express code
var express = require('express');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors =require('cors');
// MongoDB
mongoose.connect('mongodb://localhost/rest_test');
var autoIncrement = require('mongoose-auto-increment');
// Express
var app = express();
app.use(methodOverride('_method'));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes
app.use('/api', require('./routes/api'));
// Start server
app.listen(4000);
console.log('API is running on port 4000');
angular function to update the data
$scope.updateData = function (userID) {
$scope.actionData = {
"name": $scope.name,
"college": $scope.college,
"age": $scope.age
}
RoleEditF.updateUserData({
userId: userID
}, $scope.actionData).then(function (response) {
$scope.userData = response;
console.log($scope.userData)
$scope.getData();
}).catch(function (response) {
$scope.error = "Unable to get Files (code: " + response.status + "). Please try later.";
});
}
angular.module('myapp')
.factory('RoleEditF', function (updateS) {
return {
updateUserData: function (parm, data, callback) {
var cb = callback || angular.noop;
return updateS.save(parm, data,
function (res) {
return cb(res);
},
function (err) {
return cb(err);
}.bind(this)).$promise;
}
}
})
Factory to call API
angular.module('myapp')
.factory('updateS',function($resource) {
return $resource('http://localhost:4000/api/products/:userId', { userId: '#userId' }, {
update: {
method: 'PUT'
}
}, {
stripTrailingSlashes: false
});
});
I'm getting following error on browser
"NetworkError: 404 Not Found - http://localhost:4000/api/products/57161e0fe4fbae354407baa3"
it has to be 'update' in
'update': {
method: 'PUT'
}
inside your $resource() factory
documentation here
https://docs.angularjs.org/api/ngResource/service/$resource
under Creating a custom 'PUT' request

AngularJs Server Node js /get

Hello I have for this moment a fake backend with httpbackend in my angular Project. But I want to transfer my fake backend in a server node js but I don't know.
So For this moment I have this :
var express = require('express')
, path = require('path')
, fs = require('fs')
, bodyParser = require('body-parser')
, morgan = require('morgan');
var apps = express();
var staticRoot = __dirname + '/';
apps.set('port', (process.env.PORT || 3000));
apps.use(express.static(staticRoot));
apps.use(bodyParser.urlencoded({ extended: false }));
apps.use(bodyParser.json());
apps.use(morgan('dev'));
apps.use(function (req, res, next) {
var ext = path.extname(req.path);
if (ext !== '') {
return next();
}
});
apps.get('/getTpl', function (req, res) {
res.writeHead(200);
res.end(JSON.parse(["tp1", "tp2", "tp3", "tp4", "tp5", "tp6", "tp7"]));
});
apps.listen(apps.get('port'), function () {
console.log('serveur en route, port : ', apps.get('port'));
});
My controller :
ctrl.tpls = [];
ctrl.tplJson = undefined;
diapoService.getTpl().then(function (response) {
ctrl.tpls = JSON.stringify(response.data);
console.log(response.data);
});
function getTpl() {
return $http({
method: 'GET'
, url: '/getTpl'
});
I want to send my array in my select but my select is empty why ? please
Thank you so much for your answer
You have to change this function:
apps.get('/getTpl', function (req, res) {
res.status(200).json(["tp1", "tp2", "tp3", "tp4", "tp5", "tp6", "tp7"]);
});
Additionally I do not use Angular, but I don't think that you have to stringify the response:
diapoService.getTpl().then(function (response) {
ctrl.tpls = JSON.stringify(response.data); // <- Is this necessary?
console.log(response.data);
});

Angular $http POST gets null from ExpressJS

I'm inexperienced in backend and working with Node and trying to set up an $http POST request to send a form to Express. Each time I make the request, my callback data is null. Perhaps my Express routes are not configured correctly? I'm using Angular to communicate with Express/Node to send an email through nodemailer (which I've already properly configured).
Here is my $http POST request:
client/service/emailer/emailer.js
angular.module('public').factory('EmailerService',function($http) {
return {
postEmail: function(emailData, callback) {
console.log('call http with object', emailData);
$http({
method: 'POST',
url: 'http://my-website.com/server/routes/emailer',
data: emailData,
headers: { "Content-Type": "application/json" },
responseType: 'json'
}).success(function(data, status, headers, config) {
console.log('success', data, status);
}).error(function(data, status, headers, config) {
console.log('error', data, status);
}).catch(function(error){
console.log('catch', error);
});
}
};
});
Here is my server side Express configuration:
server/routes/emailer.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var logger = require('morgan');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger('dev'));
app.post('/emailer', function(req,res) {
// NOTHING LOGS HERE
console.log(res, req, req.body, res.body);
});
module.exports = app;
Nothing logs to the console here, and the error handling on the $http request returns this:
emailer.js:4 call http with Object {email: "asdf"}
angular.js:8632 OPTIONS http://matt-mcdaniel.com/server/routes/emailer net::ERR_CONNECTION_TIMED_OUT(anonymous function) # angular.js:8632sendReq # angular.js:8426$get.serverRequest # angular.js:8146deferred.promise.then.wrappedCallback # angular.js:11682deferred.promise.then.wrappedCallback # angular.js:11682(anonymous function) # angular.js:11768$get.Scope.$eval # angular.js:12811$get.Scope.$digest # angular.js:12623$get.Scope.$apply # angular.js:12915(anonymous function) # angular.js:19264jQuery.event.dispatch # jquery.js:4676jQuery.event.add.elemData.handle # jquery.js:4360
emailer.js:14 error null 0
emailer.js:16 catch Object {data: null, status: 0, headers: function, config: Object, statusText: ""}
For good measure, and since I'm new to learning Express, I'll post my server side app.js.
server/app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression');
var routes = require('./routes/index');
var contact = require('./routes/emailer');
var app = express();
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(compression());
app.use(require('connect-livereload')({
port: 35729,
ignore: ['.js']
}));
/** Development Settings */
if (app.get('env') === 'development') {
// This will change in production since we'll be using the dist folder
app.use(express.static(path.join(__dirname, '../client')));
// This covers serving up the index page
// app.use(express.static(path.join(__dirname, '../client/.tmp')));
// app.use(express.static(path.join(__dirname, '../client/public')));
// Error Handling
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
/**
* Production Settings
*/
if (app.get('env') === 'production') {
// changes it to use the optimized version for production
app.use(express.static(path.join(__dirname, '/dist')));
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
}
module.exports = app;
app.use(function(req, res) {
res.sendfile(__dirname + '/dist/index.html');
});
Here is my file Structure:
You've definitely got some problems in your emailer.js route. You should only have routing logic there, you shouldn't be recreating your express app. Express gives you a Router object to make this easy. For example, your emailer.js could look like this:
module.exports = express.Router()
.post('/emailer', function(req,res) {
console.log(res, req, req.body, res.body);
res.json({hello:'world'});
});
And you can map this route in server/app.js like so:
var emailer = require('./routes/emailer');
// ...After all app.use statements, but *before* your error handlers
app.use('/server/routes', emailer);

Issue with POST in Angular JS

I am trying to POST data using angular+ node j to my REST service running in jetty.
Here is the code:
var app =
angular.module("loginapp", []);
app.controller("loginctrl", function($scope,$http) {
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.config(['$sceDelegateProvider', function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['self', 'http://localhost:9011/**']);
}]);
$scope.login = function(e){
console.log('clicked login...');
e.preventDefault();
$http({
url: "http://localhost:9011/test/dummy/doStuff1",
method: "POST",
data : {email: $scope.email, password: $scope.password},
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
withCredentials: false,
}).success(function (data, status, headers, config) {
console.log('status',status);
console.log('data',JSON.stringify(data));
console.log('headers',headers);
});
}
});
However the data which i am passing in the Request is not getting mapped to the method argument in the REST service due to which the method is not getting invoked.Here is the code:
#Path("/test/dummy")
public class DummyService {
#POST
#Consumes({MediaType.APPLICATION_FORM_URLENCODED})
#Produces({ MediaType.APPLICATION_JSON})
#Path("/doStuff1")
public Response doStuff1(DummyParam param) {
System.out.println("Hiiiiiiiiii : ");
return Response.ok().build();
}
Without the param argument the method gets invoked however with it its not working.
The server file is :
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var cor = require("cors");
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cor());
app.all("/*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
if (req.method === 'OPTIONS') {
res.statusCode = 204;
return res.end();
} else {
return next();
}
});
app.get('/',function(req,res) {
res.sendFile(__dirname +'/test/test.html')
})
app.listen(3000);
console.log("Running at Port 3000");
Can anyone help me how to resolve this issue?
Thanks
If you see the from data coming correctly then it has to be something with setting bodyParser correctly, I had the same problem and solved it with bodyParser extension for json file. In Express.js it looks like this.
app.use(bodyParser.json());
My last guess is that maybe you need cookie-parser as well
Try to add it after body-parser:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser('SecretCode!'));
I still deepen my knowledge about express/node, but maybe it will help if not i suggest you to disconnect you api on small parts so it is easier to see what's wrong.

Upload images to a different domain nodejs

Background
I tried to use angular-file-upload module to upload the images from localhost:3000 to localhost:9000 which I assume they are different domain and should belongs to CORS (Cross-origin resource sharing). I see this module supports CORS. I also follow the express server setup that they recommend here. but still I can not see anything in either the body object or files object in the request.
Questions
Since this module supports CORS, why seems still not work.
Should I explicitly tell node server to set up something in the responds header like
(Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Allow-Headers)
and how to do that in express ?
res.setHeader(.....) ?
How can I fix this problem?
Code
/* ***************************** ANGULAR ***************************************** */
var myApp = angular.module('myApp', ['angularFileUpload']);
myApp.controller('MyCtrl', [ '$scope', '$upload', function($scope, $upload) {
$scope.$watch('files', function(files) {
if (files) {
for (var i = 0; i < $scope.files.length; i++) {
var file = $scope.files[i];
$scope.upload = $upload.upload({
url: 'http://localhost:9000/upload/',
data: {myObj: $scope.myModelObj},
file: file,
}).progress(function(evt) {
console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total) + '% file :'+ evt.config.file.name);
}).success(function(data, status, headers, config) {
console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
});
}
}
});
}]);
/* ***************************** SERVER SIDE ***************************************** */
var multipart = require('connect-multiparty');
var express = require('express');
var bodyParser = require('body-parser')
var _ = require('underscore');
var path = require('path');
var app = express();
app.use(multipart({
uploadDir: './uploads'
}));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use(function (req, res, next) {
console.log(req.files); // {} why ????
console.log(req.body); // {} why ????
});
app.listen(9000);
Actually, I figure it out by using a middleware called cors. so the server code looks like this
var multipart = require('connect-multiparty');
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser')
var app = express();
app.use(multipart({
uploadDir: './uploads'
}));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// cors middleware
app.use(cors());
app.use(function (req, res, next) {
console.log(req.files); // then there is something : )
next();
});
app.listen(9000);

Resources