req.body is undefined in express 4.13.1 - angularjs

i have a problem and i don't know the problem. Please, help me to find the solution.
In the Angular view i have:
<form ng-submit="submit()">
<input ng-model="stickie_text" type="text" id="sticky_content" />
<button type="submit" id="add_sticky" value="add a new stickie!">new sticky</button>
In the client side (AngularJS) i have this controller:
dcuApp.controller('rankingController', ['$scope', '$http',function($scope, $http) {$scope.submit = function(){
// console.log("holaaaa");
console.log($scope.stickie_text);
$http.get('/api/get-ranking',{"valor":$scope.stickie_text}).then(function(response) {
$scope.data = response.data;
console.log("RANKING: "+$scope.data);
},
function(response) {
console.debug('Error:' + response);
});
};
}]);
In the server side (Express 4.13.1) i have:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var db = require('../model/db');
var model = require('../model/model');
var fs = require('fs');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override'); //used to manipulate POST
router.use(bodyParser.urlencoded({ extended: true }))
router.use(methodOverride(function(req, res){
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
var method = req.body._method
delete req.body._method
return method
}
}));
router.get('/api/get-ranking',function(req,res,next){
console.log(req.body.valor);
});
The problem is that req.body.valor is UNDEFINED.
I know there are other postings that relate to this problem, but have not managed to fix it.
Please, I need help to get on the server side, a different req.body.valor to undefined
thanks!!! :)

You are trying to do a GET request and send data along with it. You need to use POST request to achieve what you want. You cannot send data in a GET request.
You need to change your current GET method to POST.
Replace :
router.get('/api/get-ranking',function(req,res,next){
console.log(req.body.valor);
});
with
router.post('/api/get-ranking',function(req,res,next){
console.log(req.body.valor);
});
also,
Replace :
$http.get('/api/get-ranking',{"valor":$scope.stickie_text})
with:
$http.post('/api/get-ranking',{"valor":$scope.stickie_text})
Hope this helps.

Related

Getting 404 trying http PUT using Node Express Postgresql

Edit: NEVERMIND - I made a small mistake in the Angular service. My bad.
I'm trying to teach myself more backend by building a simple CMS using angular, Node and Express, and PostgreSql. I figured out how to do achieve all the CRUD functionality except UPDATE. I thought I understood what to do but I can't figure out where I'm going wrong. I keep getting a 404. What am I misunderstanding or going about the wrong way? I know this is simple but I'm pretty new so any help in understanding where I'm getting confused is really appreciated. Here's the relevant code:
HTML
<form ng-submit="updateBlogEntry(specificBlog.id, specificBlog.title, specificBlog.author, specificBlog.imageurl, specificBlog.content)">
<h2>Title:</h2>
<input type="text" ng-model="specificBlog.title"></input>
<br>
<h3>Author:</h3>
<input type="text" ng-model="specificBlog.author"></input>
<br>
<h3>Photo:</h3>
<input type="text" ng-model="specificBlog.imageurl"></input>
<br>
<h3>Content:</h3>
<textarea type="text" rows="5" cols="50" ng-model="specificBlog.content">
</textarea>
<br>
<button type="submit">Save Changes</button>
</form>
Angular Controller
var id = $stateParams.id;
var title = $stateParams.title;
var author = $stateParams.author;
var imageurl = $stateParams.imageurl;
var content = $stateParams.content;
$scope.updateBlogEntry = function(id, title, author, imageurl, content) {
adminService.updateBlogEntry(id, title, author, imageurl, content);
}
Angular Service
this.updateBlogEntry = function(id, title, author, imageurl, content) {
return $http({
method: 'PUT',
url: 'updateBlogEntry/' + id,
data: {
id: id,
title: title,
author: author,
imageurl: imageurl,
content: content
}
})
.success(function(data) {
alert("Entry Updated");
})
.error(function(data) {
alert("Error Updating");
})
Server Index
// EXTERNAL MODULES //
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var massive = require('massive');
// CONFIG //
var config = require('./config');
// EXPRESS //
var app = module.exports = express();
app.use(express.static(__dirname + './../dist'));
app.use(bodyParser.json());
// MASSIVE //
var massiveUri = config.MASSIVE_URI;
var massiveServer = massive.connectSync({
connectionString: massiveUri
});
app.set('db', massiveServer);
var db = app.get('db');
var dbSetup = require('./services/dbSetup');
dbSetup.run();
// CONTROLLERS //
var userCtrl = require('./controllers/userCtrl');
var blogCtrl = require('./controllers/blogCtrl');
// Blog Endpoints //
app.post('/api/createBlogEntry', blogCtrl.createBlogEntry);
app.get('/api/getBlogEntries', blogCtrl.readBlogEntries);
app.get('/api/getBlogEntry/:id', blogCtrl.readBlogEntry);
// BUG Why isn't this working?
app.put('/api/updateBlogEntry/:id', blogCtrl.updateBlogEntry);
// CONNECTIONS //
var port = config.PORT;
app.listen(port, function() {
console.log('Listening on port ' + port);
});
Node Controller
updateBlogEntry: function(req, res, next){
db.blogs.blog_update([
req.params.id,
req.body.title,
req.body.author,
req.body.imageurl,
req.body.content
],
function(err, results){
if (err){
console.error(err);
res.send(err);
} else {
res.send(results[0]);
}
})
}
blog_update.sql
UPDATE blogs
set
title = COALESCE($2, title),
author = COALESCE($3, author),
imageurl = COALESCE($4, imageurl),
content = COALESCE($5, content)
WHERE id = $1
RETURNING * ;
The error in the console:
angular.js:11881 PUT http://localhost:3000/updateBlogEntry/1 404 (Not Found)
You have written your URL wrong.
It should be /api/updateBlogEntry as per your Node's express routes.
change this part
` url: 'updateBlogEntry/' + id,`
It should be
url: '/api/updateBlogEntry/' + id,

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

POST returns 404 Not Found

I've recently started using MEAN Stack to create a basic application, so im a total beginner, I set up my controllers and everything and I want to post, however it returns api/user not found, can someone pinpoint the problem and help me out? Thanks.
Server.js:
var app = require ('./app/app');
var signupController = require ('./server/signup-controller');
app.post('api/users', signupController.create);
app.listen('8080', function(){
console.log('[OK] => HTTP Server listening on http://localhost:8080');
require('./app/db').init('mongodb://localhost:27017/shopialmedia' );
});
Server side Controller (signup-controller.js):
module.exports.create = function (req, res) {
console.log(req.body);
}
Client Side Controller (signup-controller.js):
app.controller('signupController', ['$scope', '$resource', function ($scope, $resource) {
var User = $resource('/api/users');
$scope.createUser = function () {
var user = new User();
user.email = $scope.userEmail;
user.password = $scope.userPass;
user.firstName = $scope.userFName;
user.lastName = $scope.userLName;
user.age = $scope.userAge;
user.$save(function (result){
$scope.user.push(result);
$scope.userEmail = '';
$scope.userPass = '';
$scope.userFName = '';
$scope.userLName = '';
$scope.userAge = '';
});
}
}]);
My module :
var app = angular.module('signupApp', ['ngResource']);
My app.js :
var express = require ('express');
var app = express();
app.use(express.static('public'));
require('./routes')(app);
module.exports = app;
When I go to run the application on my web page and submit the information, it returns api/user 404 Not found any suggestions on what to do, I'd greatly appreciate it. As I said im a beginner so please take that into consideration.
Server.js Add:
app.get('api/users', signupController.list);
signup-controller.js Add:
mongoose = require('mongoose'),
User = mongoose.model('User');
module.exports.list = function(req, res){
var searcher = req.query || {};
User.find(searcher)
.sort('-created')
.exec(function (err, users) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
res.json(users);
});
};
Obviously, you'll also have to connect to mongoose with a file probably called main.js then you'll need a UserModel.js (or equivalent) where you can define the attributes of your user etc using the mongoose Schema...
I mean you're missing a lot if you want something a little simpler to start you can just do:
module.exports.list = function(req, res){
var users = [];
res.json(users);
};
Also think you need this and this is also nicer formatting:
var router = express.Router();
router.route('/')
.get(users.list)
.get(users.create)
app.use('/api/users', router);
Not sure what this is supposed to do or what ./routes is: require('./routes')(app);

Data insertion to mongodb with mongoose and angular

I'm new to nodejs and dived into using mongoose for mongodb. Let me show you the code structure that I made knowing that I'm doing a mistake somewhere. Suppose from angular using $http.post I'm sending an object to be inserted into db. The way I'm trying to insert the data into the database doesn't seem to work.
Mongoose Schema Contacts.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/contactlist');
var ContactSchema = new mongoose.Schema({
name: String,
email : String,
number : String
}, {collection:'contactlist'});
var ContactModel = mongoose.model('ContactList', ContactSchema);
module.exports = ContactModel;
Node server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var db = require('./model/Contacts.js');
var contact = new db();
require('./routes/routes.js')(app, db, contact);
Node routes.js
module.exports = function(app, db, contact){
// post api
app.post('/contacts', function(req,res){
var body = req.body;
contact.save(body, function(err, data){
res.json(data);
});
});
};
I'm messing up somewhere with inserting the data into database specially with the new db() and passing it to the routes file. I'm not sure what I'm missing here. And how can I improve these scripts after the insertion is solved?
Try this
Mongoose Schema Contacts.js
var mongoose = require('mongoose');
var ContactSchema = new mongoose.Schema({
name: String,
email : String,
number : String
}, {collection:'contactlist'});
var ContactModel = mongoose.model('ContactList', ContactSchema);
module.exports = ContactModel;
Node server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var contacts = require('./model/Contacts.js');
require('./routes/routes.js')(app);
mongoose.connect('mongodb://localhost/contactlist');
Node routes.js
var contacts = require('./model/Contacts.js');
module.exports = function(app){
// post api
app.post('/contacts', function(req,res){
var body = req.body;
// not sure about contact vs contacts here
contact.save(body, function(err, data){
res.json(data);
});
});
};
As part of server.js you are creating document, i.e instance of mongoose model and after that you are passing that document to exported function of routes.js module. From there you are "victim" of javascript closures. Inside of '/contacts' route handler contact will always be the same thing (document that you passed from server.js).
Then in your route handler you are using mongoose .save() method in a wrong way, providing data which you want to save as a first parameter. Please read: http://mongoosejs.com/docs/api.html#model_Model-save,
Now lets try to force your example to work and see what will happen, surely thing that you didn't want to happen.
module.exports = function(app, db, contact) {
app.post('/contacts', function(req,res){
contact.name = req.body.name;
contact.email = req.body.email;
contact.number = req.body.number;
contact.save(function(err, data){
res.json(data);
});
});
};
With this you will end with updating always the same document, the document with same id in mongoose collection due to reasons explained at the beginning of the answer.
So what you want to do is to create new document whenever there is a POST to '/contacts'.
var Contact = require('path to Contact model');
module.exports = function(app) {
app.post('/constacts', function (req, res) {
var contact = new Contact(req.body);
contact.save(function(err) {
if(err) {...}
...
});
});
};
By the way, move mongoose.connection logic out of your models, that needs to be part of bootstraping application logic and db is probably terrible name to be used for the purposes for which you are using it.

Resources