没有“Access-Control-Allow-Origin” - 节点/Apache 端口问题

新手上路,请多包涵

我已经使用 Node/Express 创建了一个小型 API,并尝试使用 Angularjs 提取数据,但是由于我的 html 页面在 localhost:8888 上的 apache 下运行,并且节点 API 在端口 3000 上侦听,因此我得到了 No ‘Access-Control-允许来源’。我尝试使用 node-http-proxy 和 Vhosts Apache 但没有太多成功,请参阅下面的完整错误和代码。

XMLHttpRequest 无法加载 localhost:3000。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin ‘localhost:8888’。”

 // Api Using Node/Express
var express = require('express');
var app = express();
var contractors = [
    {
     "id": "1",
        "name": "Joe Blogg",
        "Weeks": 3,
        "Photo": "1.png"
    }
];

app.use(express.bodyParser());

app.get('/', function(req, res) {
  res.json(contractors);
});
app.listen(process.env.PORT || 3000);
console.log('Server is running on Port 3000')

角码

angular.module('contractorsApp', [])
.controller('ContractorsCtrl', function($scope, $http,$routeParams) {

   $http.get('localhost:3000').then(function(response) {
       var data = response.data;
       $scope.contractors = data;
   })

HTML

 <body ng-app="contractorsApp">
    <div ng-controller="ContractorsCtrl">
        <ul>
            <li ng-repeat="person in contractors">{{person.name}}</li>
        </ul>
    </div>
</body>

原文由 user1336103 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 328
2 个回答

尝试将以下中间件添加到您的 NodeJS/Express 应用程序(为了您的方便,我添加了一些注释):

 // Add headers before the routes are defined
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

(您可能需要使用 127.0.0.1 而不是 localhost 。)

原文由 jvandemo 发布,翻译遵循 CC BY-SA 4.0 许可协议

接受的答案很好,如果你喜欢更短的东西,你可以使用一个名为 cors 的插件,可用于 Express.js。

对于这种特殊情况,它使用起来很简单:

 var cors = require('cors');

// use it before all route definitions
app.use(cors({origin: 'http://localhost:8888'}));

(您可能需要使用 127.0.0.1 而不是 localhost 。)

请求源需要匹配允许的源,你也可以有多个:

 app.use(
  cors({origin: ['http://localhost:8888', 'http://127.0.0.1:8888']})
);

原文由 Fabiano Soriani 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题