How to resolve Status Code:405 Method Not Allowed with $http.post? - angularjs

My angular client has a postrequest that looks like this:
$http.post("api/login/", { foo: 'bar' }).success(function(data, status) {
$scope.hello = data;
})
The server is implemented in express:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
var express = require('express');
var request = require('request');
app.set('port', process.env.PORT || 3000);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/login', function(req, res) {
res.send({message:'hello from api/login'});
});
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
When I click 'login' I get an error:
Status Code:405 Method Not Allowed
How can I resolve this error?
github:https://github.com/dimitri-a/oauth_stuff

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

Node Js get post data as json key

NodeJS File server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var moment = require('moment');
var http = require('http');
var jwt = require('jsonwebtoken');
var config = require('./config');
var User = require('./app/models/user');
var port = process.env.PORT || 8080;
mongoose.connect(config.database);
app.set('superSecret', config.secret);
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.post('/onboardAuthentication', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
res.setHeader('contentType', 'application/x-www-form-urlencoded;charset=utf-8;');
res.json(req.body);
});
var server = http.createServer(app);
server.listen(port);
console.log('Magic happens at http://localhost:' + port);
Angular API Hit Code where Front side API hit
var serviceRoot='http://localhost:8080/onboardAuthentication';
var deferred=$q.defer();
var req = {
method: 'POST',
url: serviceRoot,
data: { key: 'value' },
contentType: 'application/x-www-form-urlencoded;charset=utf-8;'
};
$http(req).then(goodResponse,badResponse);
return deferred.promise;
function goodResponse(response)
{
console.log("Good response");
console.log(response);
}
function badResponse(response)
{
console.log("Bad response");
console.log(response.data);
}
It print result in this formate, it make post data as key and value is blank, but i want to access post data in json format using body-parsar node js.
{"key":"value"}: ""
If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work,
by default angular will send application/json to the server.
var req = {
method: 'POST',
url: serviceRoot,
data: { key: 'value' },
// comment this line, you don't need it
//contentType: 'application/x-www-form-urlencoded;charset=utf-8;'
};

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

Angular $http POST gets null from ExpressJS

I'm inexperienced in backend and working with Node and trying to set up an $http POST request to send a form to Express. Each time I make the request, my callback data is null. Perhaps my Express routes are not configured correctly? I'm using Angular to communicate with Express/Node to send an email through nodemailer (which I've already properly configured).
Here is my $http POST request:
client/service/emailer/emailer.js
angular.module('public').factory('EmailerService',function($http) {
return {
postEmail: function(emailData, callback) {
console.log('call http with object', emailData);
$http({
method: 'POST',
url: 'http://my-website.com/server/routes/emailer',
data: emailData,
headers: { "Content-Type": "application/json" },
responseType: 'json'
}).success(function(data, status, headers, config) {
console.log('success', data, status);
}).error(function(data, status, headers, config) {
console.log('error', data, status);
}).catch(function(error){
console.log('catch', error);
});
}
};
});
Here is my server side Express configuration:
server/routes/emailer.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var logger = require('morgan');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger('dev'));
app.post('/emailer', function(req,res) {
// NOTHING LOGS HERE
console.log(res, req, req.body, res.body);
});
module.exports = app;
Nothing logs to the console here, and the error handling on the $http request returns this:
emailer.js:4 call http with Object {email: "asdf"}
angular.js:8632 OPTIONS http://matt-mcdaniel.com/server/routes/emailer net::ERR_CONNECTION_TIMED_OUT(anonymous function) # angular.js:8632sendReq # angular.js:8426$get.serverRequest # angular.js:8146deferred.promise.then.wrappedCallback # angular.js:11682deferred.promise.then.wrappedCallback # angular.js:11682(anonymous function) # angular.js:11768$get.Scope.$eval # angular.js:12811$get.Scope.$digest # angular.js:12623$get.Scope.$apply # angular.js:12915(anonymous function) # angular.js:19264jQuery.event.dispatch # jquery.js:4676jQuery.event.add.elemData.handle # jquery.js:4360
emailer.js:14 error null 0
emailer.js:16 catch Object {data: null, status: 0, headers: function, config: Object, statusText: ""}
For good measure, and since I'm new to learning Express, I'll post my server side app.js.
server/app.js
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 compression = require('compression');
var routes = require('./routes/index');
var contact = require('./routes/emailer');
var app = express();
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(compression());
app.use(require('connect-livereload')({
port: 35729,
ignore: ['.js']
}));
/** Development Settings */
if (app.get('env') === 'development') {
// This will change in production since we'll be using the dist folder
app.use(express.static(path.join(__dirname, '../client')));
// This covers serving up the index page
// app.use(express.static(path.join(__dirname, '../client/.tmp')));
// app.use(express.static(path.join(__dirname, '../client/public')));
// Error Handling
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
/**
* Production Settings
*/
if (app.get('env') === 'production') {
// changes it to use the optimized version for production
app.use(express.static(path.join(__dirname, '/dist')));
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
}
module.exports = app;
app.use(function(req, res) {
res.sendfile(__dirname + '/dist/index.html');
});
Here is my file Structure:
You've definitely got some problems in your emailer.js route. You should only have routing logic there, you shouldn't be recreating your express app. Express gives you a Router object to make this easy. For example, your emailer.js could look like this:
module.exports = express.Router()
.post('/emailer', function(req,res) {
console.log(res, req, req.body, res.body);
res.json({hello:'world'});
});
And you can map this route in server/app.js like so:
var emailer = require('./routes/emailer');
// ...After all app.use statements, but *before* your error handlers
app.use('/server/routes', emailer);

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