"SyntaxError: Unexpected token n" in Express Node Server - angularjs

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

Related

How to post JSON object 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

req.body empty Node.js

this is my angular controller code where im passing certificationid and userid to delete certification details of a user.
$scope.deleteCertification = function(CertificationId){
var userName = $scope.userId;
var certificationId = CertificationId;
var deleteCertificationInfo = {'userName': userName, 'certificationId':certificationId};
console.log('deleteCertificationInfo*******');
console.log(deleteCertificationInfo);
userProfileService.deleteUserCertificationInfo(deleteCertificationInfo).then (function(data){
console.log($scope.Certification);
console.log('Certification Deleted');
})
}
userProfileData.deleteUserCertificationInfo = function (deleteCertificationInfo) {
var deferred = $q.defer();
$http.delete('/api/profileUpdate/deleteUserCertification', deleteCertificationInfo, {
}).success(function(res){
var deletedUserCertificationResult = res;
deferred.resolve(deletedUserCertificationResult);
$log.debug('response from certification API:['+JSON.stringify(deletedUserCertificationResult)+']');
}).error(function(err){
deferred.reject(err);
});
return deferred.promise;
};
that is written in userProfileService to call the delete API.
but in my node controller function req.body is empty. not sure where it is going. im consoling the data in front end before sending it to service . it's displayed then. but why the req.body is getting empty?
Even though you haven't posted the Express portion of your app, the best guess here is that you're not using body-parser. body-parser is an Express middleware that is required when using req.body, without adding it to your Express app, you won't be able to parse any incoming JSON or url-encoded request bodies.
const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
let app = express();
app.use(bodyParser.json()); // this will parse Content-Type: application/json
app.use(bodyParser.urlencoded({ extended: true })); // this will parse Content-Type: application/x-www-form-urlencoded
// Your routes go here
app.listen(port);
try with the follwing code, its worked for me , you shoud have this code in your node service js file
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));

socket.io is not consistently connecting

I've just added socket.io to my MEAN stack app. It's not consistent in its connections. This is what I get when I fire up the server and connect through a browser:
GET /socket.io/?EIO=3&transport=polling&t=LTnYzIi 200 1.948 ms - 3956
POST /socket.io/?EIO=3&transport=polling&t=LTnYzJL 404 1.617 ms - 66
GET /socket.io/?EIO=3&transport=polling&t=LTnYzrU 200 1.612 ms - 3956
POST /socket.io/?EIO=3&transport=polling&t=LTnYzs6 404 1.974 ms - 66
GET /socket.io/?EIO=3&transport=polling&t=LTnY-jT 200 1.652 ms - 3956
POST /socket.io/?EIO=3&transport=polling&t=LTnY-kE 404 0.975 ms - 66
However, if I stop the server and restart it the moment the browser makes the request (in the background), the client connects and it works fine. It really has to connect everytime there's a communication right?Please tell me what I'm missing.
Here's my package.json socket.io call:
"socket.io": "^1.4.6"
My app.js looks like this:
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 expressValidator = require('express-validator')
var mongodb = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/newphase1");
var async = require('async');
var config = require('./config.js');
var routes = require('./routes/index');
var api = require('./routes/api');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(favicon(__dirname + '/public/favicon(4).png'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/public')));
app.use(expressValidator({
errorFormatter: function(param, msg, value){
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg:msg,
value:value
};
}
}));
var api = require('./routes/api')(app,express,io);
app.use('/api', api);
app.get('*',function(req,res){
res.sendFile(__dirname + '/public/views/index.html');
});
io.on('connection', function(socket) {
console.log('client connected!');
});
http.listen(config.port,"127.0.0.1",function(err){
if(err){
console.log(err);
}else{
console.log('listening on port 3000');
}
})
My socket.io script file (from CDN) in my index.js(angular):
<script src="https://cdn.socket.io/socket.io-1.4.6.js"></script>
My service for socket.io:
.factory('socketio',function($rootScope){
var socket = io.connect("http://localhost:3000");
return {
on: function(eventName,callback){
socket.on(eventName,function(){
var args = arguments;
$rootScope.$apply(function(){
callback.apply(socket,args);
});
});
},
emit: function(eventName,data,callback){
socket.emit(eventName,data,function(){
var args = arguments;
$rootScope.apply(function(){
if(callback){
callback.apply(socket,args);
}
});
});
}
}
});
It does get connected, but not consistently. Any ideas?
For some reason
npm start
gave me the above inconsistency while
node app.js
works fine.

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

Resources