【问题标题】:Node,Express, Angular routing error节点,快递,角度路由错误
【发布时间】:2015-06-23 15:55:05
【问题描述】:

我正在学习 MEAN 堆栈,但目前还没有开始使用 db。我试图连接堆栈的其余部分,但它会引发错误

错误:对受限 URI 的访问被拒绝 createHttpBackend

我用谷歌搜索并找不到任何解决此问题的方法。

这是我在 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!';
    })
});

我的节点服务器 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'));
});

这是浏览器控制台中的错误(发生 Angular http.get 时):

"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

请帮帮我。

这是完整的应用程序 - https://github.com/V1cHu/routing

【问题讨论】:

  • 尝试使用其他网址而不是“/”
  • 堆栈的哪一部分抛出了这个错误?我不知道是节点应用程序在浏览器控制台中以 bash 还是 Angular 的形式抛出它
  • 角度抛出浏览器控制台。
  • @Mohit acutally 当我尝试点击链接 localhost:3000/ 时,节点控制台显示 GET 命中,但是当我使用 Angular 应用程序尝试此操作时,它根本没有命中节点服务器
  • 试试$http.get('http://localhost:3000/')而不是$http.get('/')

标签: javascript angularjs node.js express


【解决方案1】:

查看您的代码后,我发现您的代码中存在一些问题 1) 您不需要添加跨浏览器支持代码

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

还有这段代码

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

2) 在服务器端 app.js 文件中,将调用 app.get('/') 更改为其他路由,例如 app.get('/xyz'),因为它不允许您加载 Angular js代码

3)在您的主控制器 (MainCtrl) 中使用 $http.get('/xyz') ,如上更新。不要使用 $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!';
})

编辑:在服务器端 app.js 添加此代码

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

并在客户端 app.js 文件中将 $scope.name 更改为 data not data.name

  $scope.name = data;

它会解决你的问题

【讨论】:

  • 我尝试了你的每一步。它仍然不起作用。我现在收到“访问受限 URI 错误”。
  • 我已经在我的机器上检查了你的代码。它工作正常
  • 请在link 上运行此代码。这是从您的仓库中分叉出来的,可以在我的机器上完美运行
  • 我运行了你的代码,但它仍然对我不起作用。它抛出相同的错误。请让我知道您究竟是如何运行代码的?我启动节点服务器,然后在浏览器中打开 index.html。
  • 进入你的目录,在命令提示符下输入“node app”,然后在浏览器中运行localhost:3000。不需要自己打开index.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多