How to post JSON object angularjs - angularjs

I would like post object and read it on node server but I have an error.
controller :
$scope.update = function(contact) {
console.log(contact);
$http.post('/contactlist/' + contact).then(function(response) {
console.log(response);
});
};
server node :
app.post('/contactlist/:contact', function (req, res, next) {
console.log(req.body);
res.json();
});
server node head:
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var connection = *****************
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname + "/public"));
Screenshot of the error network POST :
enter image description here
server error of console.log(req.body);
[object Object]
SyntaxError: Unexpected token o in JSON at position 1

You are not passing any parameter in your post API. POST needs a parameter to be passed and since you are passing the parameter in the request URL, you can try by passing an empty object like this:
$http.post('/contactlist/' + contact,{}).then(function(response) {
console.log(response);
});
You are trying to concatenate an object in the URL which is not a good approach. If you want to still do this way, stringify it and then append it to URL. And you can get it with the help of req.query. But it is better if you change the url and pass contact as a parameter to your API call.
Problem solved by :
var OBJ = JSON.stringify(yourOBJ);

For node js there different syntax please see below:
var yourObj = {};
$http.post('/contactlist/' + contact, {data: yourObj}).then(function(response)
{
console.log(response);
});
This will work

Related

XMLHttpRequest cannot load [url] Response for preflight is invalid (redirect)

I'm making an ionic app for android and today I implemented a server side nodejs (express) Restful API with mongodb on cloud9.
But when I trigger a http request to the url, I keep getting the error mentioned in the title:
This is my angular http request on ionic (simply to test first):
app.controller('DashCtrl', function($scope, $http, $q) {
$http.get('https://[workspace]-[user].c9users.io/api/capture')
.then(function(result) {
console.log(result);
});
});
This is an image of my workspace:
I used the following code to make the database:
api.js
var Capture = require('../models/capture');
module.exports = function(router) {
router.get('/capture', function(req, res){
var capture = new Capture();
// capture.birdname = req.body.birdname;
// capture.place.city = req.place.body.city;
// capture.place.country = req.place.body.country;
capture.birdname = "Pigeon";
capture.save(function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.get('/captures', function(req, res){
Customer.find({}, function(err, data){
res.json(data);
})
})
}
capture.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var captureSchema = mongoose.Schema({
birdname: String,
place: {
city: String,
country: String
}
});
module.exports = mongoose.model('Capture', captureSchema)
database.js
module.exports = {
'url': 'mongodb://' + process.env.IP
}
server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var configDB = require('./server/config/database.js');
mongoose.connect(configDB.url);
var api = express.Router();
require('./server/routes/api')(api);
app.use('/api', api);
app.listen(process.env.PORT, process.env.IP);
console.log('Listening on port ' + process.env.PORT)
Anyone have an idea why I'm getting this error and what I need to do to fix this?
I'm guessing it has something to do with the server allowing me to send requests to the API though I don't know how to implement that.
Is there also a way to secure my database (API key maybe) and how would I implement this?
Thanks in advance

Getting angularJS $http.post from nodeJS

Please help me, I would like to get angularJS $http.post parameter that being sent to be processed in nodeJS.
I would like to see whether the parameter (nama, nip, pernr, etc...) was sent successfully, but the result is undefined as shown below :
angularJS code :
// ADMINISTRATOR ========================================
.state('talentapegawai.uploadtalenta.douploadtalenta', {
views:{
"monitorupload": {
url: '/douploadtalenta',
templateUrl: '/progressupload.html',
controller:function($scope, $http, XLSXReaderService){
$scope.prograssing2 = true;
for(var i=0; i < $scope.sheets[$scope.selectedSheetName].length; i++){
$http.post("/execuploadtalenta",{'nama': $scope.sheets[$scope.selectedSheetName][i].nama, 'nip': $scope.sheets[$scope.selectedSheetName][i].nip, 'pernr':$scope.sheets[$scope.selectedSheetName][i].pernr, 'tgl_grade_terakhir': $scope.sheets[$scope.selectedSheetName][i].tgl_grade, 'singkatan_talenta': $scope.sheets[$scope.selectedSheetName][i].talenta_abbr, 'talenta': $scope.sheets[$scope.selectedSheetName][i].talenta, 'mulai':$scope.sheets[$scope.selectedSheetName][i].mulai, 'akhir':$scope.sheets[$scope.selectedSheetName][i].akhir})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
}
$scope.prograssing2 = false;
}
}
}
})
NodeJS code (express) :
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/execuploadtalenta', requireLogin, function (req, res) {
console.log("NILAI REQUEST : "+req.body.nama); -->return undefined
console.log("NILAI REQUEST : "+req); -->return [object, object]
});
server.listen(3333);
First of, Tell body-parser to parse json requests:
app.use(bodyParser.json({limit: '10mb'}));
Its also a good practice to limit the size of json objects
Then, You should be able to read the body as a JSON object.
Take a troubleshooting tip, just to make sure what you get in the body is correct, you can print it as string:
console.log(JSON.stringify(req.body));

"SyntaxError: Unexpected token n" in Express Node Server

I get this error-
SyntaxError: Unexpected token n
at parse (/Users/afroza/node_modules/body-parser/lib/types/json.js:83:15)
at /Users/afroza/node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/Users/afroza/node_modules/raw-body/index.js:262:16)
at done (/Users/afroza/node_modules/raw-body/index.js:251:7)
at IncomingMessage.onEnd (/Users/afroza/node_modules/raw-body/index.js:308:7)
at IncomingMessage.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
I creating a route with nodejs and I'm getting this error,I've tried many things and there's no way, always appears this error,
my server setup in express framework-
var express = require('express');
var app = express()
, fs = require('fs')
, path = require('path');
var env = process.env.NODE_ENV || 'production'
, config = require('./config/config')[env]
, mongoose = require('mongoose');
var http = require('http');
var db = mongoose.connect('mongodb://localhost/orbitax');
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser'); // add body-parser for interact with server and client data
var jsonParser = bodyParser.json(); //join this body parser with json file
var urlencodedParser = bodyParser.urlencoded({ extended: false});
//Initialize Models
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
require(models_path+'/'+file)
});
require('./config/routes')(app,config);
var server = app.listen(9000, function(){
var host = server.address().address;
var port = server.address().port;
});
server routing,
var async = require('async')
, mongoose = require('mongoose')
, uploadModel = mongoose.model('uploadModel');
module.exports = function (app) {
// upload routes
var upload = require('../app/controller/upload');
app.get('/newUpload', upload.newUpload);
app.post('/create_new_directory', upload.create_new_directory);
}
exports.create_new_directory = function(req, res)
{
console.log("hello")
console.log(req.body);
}
and from client side request is,
$http({'method': 'post', 'url': '/create_new_directory', data: $scope.directory })
.success(function(data){
console.log(data)
})
.error(function(){
})
Any help would be appreciated, Thanks.
By default, the $http service will only transform request data to a JSON string if the data is an object.
https://github.com/angular/angular.js/blob/v1.4.8/src/ng/http.js#L292
In your case, the request data is a string so it is not getting wrapped in quotes, making it invalid JSON.
You should be able to modify your $http config like this:
$http({
method: 'POST',
url: '/create_new_directory',
data: $scope.directory,
transformRequest: JSON.stringify
}).success(function(data){
console.log(data)
})

angular js post request to nodejs json. key undefined express 4

https://codeforgeek.com/2014/07/angular-post-request-php/
Hi I was following the above link to give post request from angular js to node js. I received the data posted in below format when i give
console.log(req.body);
{ '{"email":"test#test.com","pass":"password"}': '' }
and when i try to get the value as below, it says undefined.
var email = req.body.email;
console.log(email);
I am unable to get the value of email and pass. Thank you
change the client side header code to headers: { 'Content-Type': 'application/json' }
Your Angular code is sending JSON data, but your Express app is parsing it as URL encoded data.
You probably have something like this in your Express app:
var bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded());
That last line should be:
app.use(bodyParser.json());
You did not well explain the problem , please next time try to post a bigger part of your code so we could understand what you wanted to do / to say .
To answer your question i will copy/paste a part of my code that enable you to receive a post request from your frontend application(angularJS) to your backend application (NodeJS), and another function that enable you to do the inverse send a post request from nodeJS to another application (that might consume it):
1) receive a request send from angularJS or whatever inside your nodeJS app
//Import the necessary libraries/declare the necessary objects
var express = require("express");
var myParser = require("body-parser");
var app = express();
// we will need the following imports for the inverse operation
var https = require('https')
var querystring = require('querystring')
// we need these variables for the post request:
var Vorname ;
var Name ;
var e_mail ;
var Strasse ;
app.use(myParser.urlencoded({extended : true}));
// the post request is send from http://localhost:8080/yourpath
app.post("/yourpath", function(request, response ) {
// test the post request
if (!request.body) return res.sendStatus(400);
// fill the variables with the user data
Vorname =request.body.Vorname;
Name =request.body.Name;
e_mail =request.body.e_mail;
Strasse =request.body.Strasse;
response.status(200).send(request.body.title);
});
2) Do the inverse send a POST request from a nodeJS application to another application
function sendPostRequest()
{
// prepare the data that we are going to send to anymotion
var jsonData = querystring.stringify({
"Land": "Land",
"Vorname": "Vorname",
"Name": "Name",
"Strasse": Strasse,
});
var post_options = {
host: 'achref.gassoumi.de',
port: '443',
method: 'POST',
path: '/api/mAPI',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': jsonData.length
}
};
// request object
var post_req = https.request(post_options, function(res) {
var result = '';
res.on('data', function (chunk) {
result += chunk;
console.log(result);
});
res.on('end', function () {
// show the result in the console : the thrown result in response of our post request
console.log(result);
});
res.on('error', function (err) {
// show possible error while receiving the result of our post request
console.log(err);
})
});
post_req.on('error', function (err) {
// show error if the post request is not succeed
console.log(err);
});
// post the data
post_req.write(jsonData);
post_req.end();
// ps : I used a https post request , you could use http if you want but you have to change the imported library and some stuffs in the code
}
So finally , I hope this answer will helps anyone who is looking on how to get a post request in node JS and how to send a Post request from nodeJS application.
For further details about how to receive a post request please read the npm documentation for body-parser library : npm official website documentation
I hope you enjoyed this and Viel spaß(have fun in german language).

In Express.js with body-parser the value of request.body is undefined

I'm having a problem I cannot diagnose.
On a server, I have a simple URL handler using Express.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
app.configure(function() {
app.use(app.router);
app.use(bodyParser.json()); // see: http://expressjs.com/api.html#req.body
app.use(bodyParser.urlencoded({
extended: true
}));
});
app.post('/submit', function (req, res) {
console.log(req.body);
});
On client side, there's a form which is handled with Angular controller:
$scope.submit = function () {
// $http.post('/submit', $scope.data); // POST request to send data to the server
$http({
method: 'POST',
url: '/submit',
data: $scope.data
});
console.log('POST /submit ' + JSON.stringify($scope.data));
};
In browser's console everything is fine: $scope.data is valid; Node.js also responds with console.log, as expected, but writes undefined which means that, well, request.body is undefined.
What do I do wrong? How can I fix it?
If you're using Express 3 you shouldn't have to use the body-parser module as it is already bundled with Express 3 as express.bodyParser. You're getting an empty body because you're putting app.use(app.router) before the body parser.
app.configure(function() {
app.use(express.bodyParser());
app.use(app.router);
});
Which is why your other solution is working:
app.post('/submit', bodyParser.json(), function (req, res) {
Well, I just came up with solution, and it works. Here the app.post using body-parser is explained in few words. So I changed POST request handler definition to:
app.post('/submit', bodyParser.json(), function (req, res) {
console.log(req.body);
});
And now not only console.log(req.body) returns valid data, but it's deserialized into JSON correctly on the server without any extra code (which is, well, expected from Angular+Node pair).

Resources