I am creating a MEAN stack application using AngularJS and Node.js.
Here is my AngularJS code:
app.js:
var app = angular.module('crudApp', ['ngRoute']);
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider){
$routeProvider
.when('/employees/create', {
templateUrl : 'create.html',
controller : 'EmployeeController'
}).when('/nothing', {
templateUrl : 'main.html',
controller : 'mainController'
});
$locationProvider.html5Mode(true);
}]);
app.controller('EmployeeController',function($scope,$http) {
$scope.save = function(data) {
$scope.data = JSON.stringify(data);
console.log(data);
$http.post("http://localhost:8080/employees/create-employee",$scope.data).then(function(response) {
console.log("posted successfully");
});
};
});
Here is my Node.js code:
server.js:
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(express.static(__dirname + '/angularjs/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('*',function(req, res) {
res.sendFile(__dirname + '/angularjs/public/index.html');
});
require('./node/routes')(app);
app.listen(8080);
routes.js:
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.body);
});
Angular part is working fine, displays data in console, posting the data and getting "posted successfully" message.
But in node, I am unable to get the posted data in req.body.
I am getting the "create.html" content when I checked in browser "network".
Need someone's help.
Use this
module.exports = function(app) {
app.post('/employees/create-employee',function(req,res) {
console.log(req.body);
});
And for get you should use req.params
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.params);
});
Related
I am building a simple MySQL, Express, Angular, Node app and using Sequelize as my ORM. When I create a new survey, the values I am sending do not get set, as the req.body is an empty object.
server.js
'use strict';
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var bodyParser = require('body-parser');
var models = require('./server/models/');
var routes = require('./server/routes');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(process.cwd() + '/public'));
//App routes
app.use(routes(express.Router()));
app.get('/*', function (req, res) {
res.sendFile('index.html', {
root: './public'
});
});
app.listen(port, function() {
console.log('Server running on port %s ', port);
});
app.js
'use strict';
// Declare app level module which depends on views, and components
var app = angular.module('myApp', []);
app.controller('SurveyController', ['$scope', '$http', function($scope, $http) {
//Get all Surveys
$http.get("/surveys")
.then(function(response) {
$scope.surveys = response.data;
});
$scope.create = function() {
$http.post("/surveys",{
question: $scope.question,
answers: $scope.answers,
user: $scope.user
})
.then(function(response) {
});
}
}]);
model
'use strict';
module.exports = function(sequelize, DataTypes) {
var Survey = sequelize.define('Survey', {
question: DataTypes.STRING,
answers: DataTypes.STRING,
user: DataTypes.STRING
}, {
underscored: true,
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Survey;
};
routes.js
var surveys = require('./controllers/surveys');
module.exports = function (router) {
//routes
router.get('/surveys', surveys.get);
router.get('/surveys/:id', surveys.getOne);
router.post('/surveys', surveys.create);
router.put('/surveys', surveys.update);
router.delete('/surveys', surveys.delete);
return router
};
controller
//Create a new survey
create: function(req, res) {
//this req.body and req.params are both empty
Survey.create(req.body)
.then( function(newSurvey) {
res.status(200).json(newSurvey);
})
.catch( function(error) {
res.status(500).json(error);
})
},
I recently had a similar problem here: Why is my req.body always empty on POST? but the solution for that did not work for this issue. I am presuming it is similar but the solution has alluded me so far.
Don't need to stringify
$http
.post("/surveys", {
question: $scope.question,
answers: $scope.answers,
user: $scope.user
},
{
headers: { 'Content-Type': 'application/json; charset=UTF-8'}
})
Per many comments above (many thanks to all), I solved this by changing my bodyParser implementation from
app.use(bodyParser.urlencoded({
extended: true
}));
to
app.use( bodyParser.json() );
I am learning node and express to create an api for an angular app I will be creating.
When I try and post something the req.body seems to be blank.
This is my server.js file
'use strict';
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
router = require('./api'),
bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/my_db');
app.use(bodyParser.json());
app.use('/api', router);
app.get('/', function(req, res) {
res.render(__dirname + '/index.jade');
});
app.listen(3001, function() {
console.log('Listening on port 3001');
});
and this is my api/index.js file:
'use strict';
var express = require('express'),
Todo = require('../models/todo'),
router = express.Router();
router.get('/todos', function(req, res) {
Todo.find({}, function(err, todos) {
if(err) {
return console.log(err);
}
res.json({todos: todos});
});
});
router.post('/todos', function(req, res) {
var todo = req.body;
res.json({todo: todo});
});
module.exports = router;
when I use postman to post this to http://localhost:3001/api/todos:
{
'name': 'Walk the Dog',
'completed': false
}
my response is:
{
"todo": {}
}
I can't see why this would be blank, any help is appreciated.
UPDATE
Turns out I was posting text in postman instead of JSON.
use this in your server.js file
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
I'm using auth0 to act as my admin panel's login, and it's running great. A problem that I'm having is that in node, I cannot for some reason access 'req.user' as it returns unidentified. This is a pretty basic setup here. I have console logged req.headers and an authentication header is set.
Here is the node app.js file
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var Parse = require('node-parse-api').Parse;
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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('/bower_components', express.static(__dirname + '/bower_components'));
app.Parse = new Parse(options.app_id, options.api_key);
app.use('/api', routes(app), expressJwt({secret: 'Mode'}));
app.all('/*', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, '/public') });
});
module.exports = app;
Here is the AngularJS code.
var app = angular.module('EnragedGamers', ['angularMoment', 'ngRoute', 'auth0', 'angular-storage', 'angular-jwt'])
.config(function(authProvider, $routeProvider, $locationProvider, $httpProvider, jwtInterceptorProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'Home'
})
.when('/article/:article_id', {
templateUrl: 'article.html',
controller: 'Article'
})
.when('/admin-panel/login', {
templateUrl: 'admin-login.html',
controller: 'Admin-Login'
})
.when('/admin-panel', {
templateUrl: 'admin.html',
controller: 'Admin',
requiresLogin: true
});
authProvider.init({
domain: 'enragedgamers.auth0.com',
clientID: 'MpTkAl4eosjl3SB682ZGSSrJYi03QiZp',
loginUrl: '/admin-panel/login'
});
jwtInterceptorProvider.tokenGetter = ['store', function(store) {
// Return the saved token
return store.get('token');
}];
$httpProvider.interceptors.push('jwtInterceptor');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
})
.run(function($rootScope, auth, store, jwtHelper, $location) {
// This hooks al auth events to check everything as soon as the app starts
$rootScope.$on('$locationChangeStart', function() {
var token = store.get('token');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!auth.isAuthenticated) {
auth.authenticate(store.get('profile'), token);
}
} else {
// Either show the login page or use the refresh token to get a new idToken
$location.path('/');
}
}
});
});
Here is the routes file code
var express = require('express');
var router = express.Router();
module.exports = function(app){
router.get('/admin/hello', function(req, res){
console.log(req.user)
res.status(201).json({'human': 'Hello'})
console.log(req.body);
});
return router;
}
It seems that you're missing your secret on the node side and the middle man for actually authenticating.
See https://github.com/auth0/express-jwt
var jwt = require('express-jwt');
app.use(jwt({ secret: 'your secret key here'}));
I am pretty new to AngularJS, and even newer to ExpressJS and Mongoose. I have been following a tutorial to post to, and get from my database, but I'm having trouble adding delete functionality.
Here is where I call my delete function:
<ul ng-repeat="disease in diseases">
<li>
{{ disease.name }}: {{ disease.chipped }},
{{ disease.received }},
{{ disease.smashed }},
{{ disease.complete }}
</li>
<button ng-click="removeDisease(disease)"></button>
</ul>
... and in my controller I have:
app.controller('MainCtrl', [
'$scope',
'TrelloApi',
'diseases',
function($scope, TrelloApi, diseases){
$scope.diseases = diseases.diseases;
$scope.removeDisease = function(disease) {
console.log(disease);
diseases.destroy(disease);
}
}
]);
...which calls my diseases factory:
app.factory('diseases', [
'$http',
function($http){
var o = {
diseases: []
};
o.destroy = function(disease) {
return $http.delete('/diseases/' + disease._id).success(function(data){
console.log("Disease " + disease.name + " has been removed!");
o.getAll();
});
};
return o;
}
]);
This returns with a 404 error:
DELETE http://localhost:4000/diseases/<id> 404 (Not Found) even though in my my routes include:
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Disease = mongoose.model('Disease');
// Not functional
router.delete('/diseases/:id', function(req, res, next) {
console.log(req);
});
// Functional
router.post('/diseases', function(req, res, next) {
var disease = new Disease(req.body);
disease.save(function(err, diseases){
if(err){ return next(err); }
res.json(diseases);
});
});
... and ui.router includes:
app.config([
'TrelloApiProvider',
'$stateProvider',
'$urlRouterProvider',
function(TrelloApiProvider, $stateProvider, $urlRouterProvider) {
.state('diseases', {
url: '/diseases/{id}',
templateUrl: '/javascripts/home/_diseases.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}
]);
There is also a template found at /javascripts/home/_diseases.html. I have a feeling I am missing one piece but I just can't figure out what it is.
Be sure you start Express HTTP server:
const express = require('express');
const router = express.Router();
router.delete('/diseases/:id', function(req, res, next) {
const id = req.params.id;
console.log(id);
});
const app = express();
app.use('/', router);
const server = http.createServer(app).listen(8080, serverCallback);
function serverCallback() {
const host = server.address().address;
const port = server.address().port;
console.log(`Server listening on ${host}:${port}`);
}
So Im trying to work AngularJS and Node. I am trying to set up client side routing but Im having some problems.
EDIT
So I changed up some code following https://github.com/scotch-io/starter-node-angular that #PareshGami suggested. I get the URLS to be hit but now the actual content doesnt load.
Here is my updated Code:
server.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
app.use(bodyParser.json());
require('./server/routes')(app);
app.use('/js', express.static(__dirname + '/client/js'));
app.use('/views', express.static(__dirname + '/client/views'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname +'/node_modules'));
app.listen(3000);
console.log('Im Listening...');
exports = module.exports = app;
my angular app.js:
(function (angular) {
'use strict';
var app = angular.module('eos', [
'ngRoute',
'ngResource',
'eos.opsCtrl',
'eos.dashboardCtrl'
]);
app.config(function ($routeProvider, $locationProvider){
$routeProvider.when(
'/',
{
templateUrl: 'views/dashboard.html',
pageName: 'Dashboard',
controller: 'dashboardCtrl'
}
);
$routeProvider.when(
'/ops',
{
templateUrl: 'views/ops.html',
pageName: 'Operations',
controller: 'opsCtrl'
}
);
$routeProvider.otherwise({redirectTo: '/'});
$locationProvider.html5Mode(true);
});
}(window.angular));
My routes.js (new):
var opsController = require('./controllers/opsController');
module.exports = function(app) {
//path.join(__dirname, 'client');
// server routes ===========================================================
// handle things like api calls
// authentication routes
app.get('/api/ops', opsController.list);
app.post('/api/ops', opsController.create);
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendFile('index.html', { root: './client' });
});
};
Then rest is identical. And suggestions on why it is not loading the content in the ng-view?
FINALLY GOT IT TO WORK! My server.js was set up wrong.
Here is the correct server.js. Notice position of:
require('./server/routes')(app);
it needed to be father down for what I assume is the compile sequence
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
methodOverride = require('method-override');
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use('/js', express.static(__dirname + '/client/js'));
app.use('/views', express.static(__dirname + '/client/views'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname +'/node_modules'));
require('./server/routes')(app);
app.listen(3000);
console.log('Im Listening...');
exports = module.exports = app;
I was directed by PareshGami to look over this site 'setting-up-a-mean-stack-single-page-application'. After following that I was able to get the routing to work. The key to my problem was the ordering of my server.js file and the require('./server/routes')(app); part.