AngularJs $resource.save returning 404 error - angularjs

I am getting a 404 error while trying to create a new JSON file locally.
Here is my service:
eventsApp.factory('eventData', function($resource){
var resource = $resource('/data/event/:id', {id:'#id'});
return {
getEvent: function() {
//return $http({method: 'GET', url:'/data/event/1'});
//return $resource('/data/event/:id', {id:'#id'}).get({id:1});
return resource.get({id:1});
},
save: function(event) {
event.id = 999;
return resource.save(event);
}
}
});
The web.server js code is as below:
var express = require('express');
var path = require('path');
var events = require('./eventsController');
var bodyParser = require('body-parser');
var app = express();
var rootPath = path.normalize(__dirname + '/../');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(rootPath + '/app'));
app.get('/data/event/:id', events.get);
app.post('/data/event:id', events.save);
app.listen(8000);
console.log('Listening on port 8000...');
The get function works perfectly fine, but the post always throws a 404 error.
See a screenshot below:
What am I missing?

As said in comments, your Express server routes are bad defined.
So when trying to POST data on /data/event/999, no route is defined for.
app.get('/data/event/:id', events.get);
app.post('/data/event/:id', events.save); // You forgot '/' here

Related

Deploying node-react app in Heroku - fetch doesn't work

I'm trying to deploy a small react app that fetches data mlab - by a node api... locally it's working - when doing fetch - it's returns data - but when deploying to heruko - i get no data back from the Api... i'm newbie to react/node so i must have done something wrong....
Here is the api :
var express = require('express');
var cors = require('cors')
var app = express();
var morgan = require('morgan');
app.use(morgan('dev'));
var port = process.env.PORT || 3007;
var mongoose = require('mongoose');
mongoose.connect('mongodb://ggg:gggg#ds235418.mlab.com:35418/redux-form');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("DB connection alive");
});
var User = require('./model/user');
var Message = require('./model/message');
var router = express.Router();
app.get('/messages',function(req, res) {
Message.find(function(err, messages) {
if (err)
res.send(err);
res.json(messages);
});
});
app.listen(port);
console.log('Magic happens on port ' + port);
And here is the redux action - from the react app
export function getMessages() {
const request = fetch(`http://localhost:3007/messages`, { method: 'GET' })
.then(response => response.json());
return {
type: 'GET_MESSAGES',
payload: request
}
}

When use body-parser module in my app , get GET ERR_EMPTY_RESPONSE

I have this Error when I'm trying to load my website
GET http://localhost:3000/ net::ERR_EMPTY_RESPONSE
I'm using Mean Stack Technologies,
When I remove app.use(bodyParser.json); from my code the page load very well
the code of my server.js file :
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
var authenticationController = require('./server/controllers/authentication-controller');
mongoose.connect('mongodb://localhost:27017/time-waste');
app.use(bodyParser.json);
app.use('/app',express.static(__dirname + '/app'));
app.use('/node_modules',express.static(__dirname + '/node_modules'));
app.get('/',function(req,res){
res.sendfile('./index.html');
});
//Authentication
app.post('/api/user/signup',authenticationController.signup);
app.listen('3000',function(){
console.log("listening on port 3000");
});
the auth controller file
var mongoose = require('mongoose');
var User = require('../datasets/users');
module.exports.signup = function(req,res){
console.log(req.body);
var user = new User(req.body);
user.save();
res.json(req.body);
};
the angular controller
angular.module('TimeWaste').controller('signUpController',['$scope','$state','$http',function($scope,$state,$http){
$scope.createUser = function(){
console.log($scope.newUser);
$http.post('api/user/signup',$scope.newUser).success(function(response){
}).error(function(error){
console.log(error);
});
};
}]);

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

Get URL param in Express API from Angular UI-Router

I can't get the param of the URL which I pass when changing the state in Angular (ui router):
.state('contact.detail', {
url: '/:contactId',
templateUrl: 'detail.html',
controller: 'DetailController'
})
In Express I define an API, but the problem is in getting the param from the URL which I passed from ui router (above).
server.js
var express = require('express');
var mysql = require('mysql');
var url = require('url');
var app = express();
app.use('/', express.static('../app'));
app.use('/bower_components', express.static('../bower_components/'));
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.jsonParser = bodyParser.json();
app.urlencodedParser = bodyParser.urlencoded({ extended: true });
//mysql connection setup
var connection = mysql.createConnection({
host : "localhost",
port: "3306",
user : "root",
password : "",
database : "db",
multipleStatements: true
});
app.get('/:id', app.urlencodedParser, function(req,res){
var id = req.params.id;
console.log(id); // => :id instead of value
connection.query('SELECT * FROM contacts WHERE contactId = ?', [id], function (error, results) {
if(error) {
throw error;
}
else {
res.end(JSON.stringify(results));
}
});
});
server.listen(3000, function () {
'use strict';
});
In log I get ":id" instead of the real value, for example "45".
I can access the API manually
Please take a look at the plunker for states details.
Since u are using ui-router (or ngRoute) , it is client side routing , if you want to call a route from your server you have to make a http call , with $http service (or $resource) , like:
//this is a example not tested.
.controller('DetailController', function($scope, $stateParams,$http){
console.log('Passed parameter contact id is:', $stateParams.contactId);
$scope.selectedContactId = $stateParams.contactId;
$http.get("localhost:3000/"+$stateParams.contactId)
.success(function(data){
//console.log(data)
})
.error(function(error,status){
})
});

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