angularjs - enabling cors in meanjs rest api server -
i creating api (server side) based on meanjs.org latest version (0.4.0) , managed pull off men part , create 1 in http://localhost:3000/api
as frontend part created angularjs in http://localhost:4000/
and run both application using (p)ackage (m)anager 2
i trying create user sending user credentials using $resource
this
angular.module('users').factory('authenticationresource', ['$resource', function($resource) { return $resource('http://localhost:3000/api/auth/signup', {}, { post: { method: 'post' } }); } ]); ... //in controller $scope.signup = function() { authenticationresource.post($scope.credentials, function(response) { $scope.authentication.user = response; $state.go($state.previous.state.name || 'home', $state.previous.params); }); };
while in server side's express.js
'use strict'; var config = require('../config'), express = require('express'), ... cors = require('cors'); ... module.exports.initmodulesserverroutes = function(app) { // globbing routing files config.files.server.routes.foreach(function(routepath) { require(path.resolve(routepath))(app); }); }; module.exports.initcorsoption = function(app){ app.options('*', cors()); }; module.exports.init = function(db) { // initialize express app var app = express(); ... // initialise cors options this.initcorsoption(app); // initialize modules server routes this.initmodulesserverroutes(app); ... return app; };
i using node cors package enable cors , app.options('*', cors());
enable pre-flight across-the-board
but when trying post
http://localhost:3000/api/auth/signup
can see user being saved database fine doesn't give me response , chrome console giving me this
xmlhttprequest cannot load http://localhost:3000/api/auth/signup. no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost:4000' therefore not allowed access.
what did miss?
i think missing app.use before routes:
only express:
app.use(function(req, res, next) { res.header("access-control-allow-origin", "*"); res.header("access-control-allow-headers", "origin, x-requested-with, content-type, accept"); next(); });
if using npm cors:
app.use(cors());
Comments
Post a Comment