v1shnu
v1shnu

Reputation: 2231

Node,Express, Angular routing error

I'm learning the MEAN stack but for now have not started with the db. I tried to wire the rest of the stack but it throws an error

Error: Access to restricted URI denied createHttpBackend

I googled and could not find any solutions to this problem.

This is my main controller in Angular app.js:

app.controller('MainCtrl', function($scope, $http) {
    console.log("success");
    $http.get('/').
    success(function(data, status, headers, config) {
        console.log("success");
        $scope.name = data.name;
    }).
    error(function(data, status, headers, config) {
        $scope.name = 'Error!';
    })
});

My node server app.js:

var express = require('express'),
    http = require('http');

var app = express();

app.set('port', 3000);

app.get('/', function(req, res) {
    var name = 'MyNameFromServer';
    res.send(name);
})

http.createServer(app).listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});

And this is the error in browser console ( when Angular http.get happens):

"Error: Access to restricted URI denied
createHttpBackend/<@file:///F:/routing/js/angular.js:9902:6
sendReq@file:///F:/routing/js/angular.js:9703:0
$http/serverRequest@file:///F:/routing/js/angular.js:9415:15

Please help me out.

This is the full app - https://github.com/V1cHu/routing

Upvotes: 3

Views: 984

Answers (1)

Mohit
Mohit

Reputation: 559

After reviewing your code,I found there are few problems in your code 1) You don't need to add that crossbrowser support code

app.all('/*', function(req, res, next) {
 res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Headers", "X-Requested-With");
 res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
 next()}
);

and also this code

$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

2) In the server side app.js file change the call app.get('/') to some other route for eg app.get('/xyz') because it does not allow you to load your angular js code

3)In your main controller (MainCtrl) use $http.get('/xyz') as updated above.Don't use $http.get('http://localhost:3000/')

$http.get('/xyz').
success(function(data, status, headers, config) {
    console.log("success");
    $scope.name = data;
}).
error(function(data, status, headers, config) {
    $scope.name = 'Error!';
})

EDIT: in server side app.js add this code

var path = require('path')
app.use(express.static(path.normalize(__dirname + '/')));

and in the client side app.js file change $scope.name to data not data.name

  $scope.name = data;

It will solve issues in your problem

Upvotes: 2

Related Questions