一尘不染

没有“访问控制允许来源”-节点/ Apache端口问题

angularjs

我使用Node /
Express创建了一个小型API,并尝试使用Angularjs提取数据,但是由于我的html页面在localhost:8888上的apache下运行,而node
API在端口3000上进行侦听,我得到了否’Access-Control-允许原产’。我尝试使用 node-http-proxy和Vhosts
Apache,但没有成功,请在下面查看完整的错误和代码。

XMLHttpRequest无法加载localhost:3000。所请求的资源上没有“ Access-Control-Allow-
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>

阅读 261

收藏
2020-07-04

共1个答案

一尘不染

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

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

希望有帮助!

2020-07-04