没有“访问-控制-允许-原产地”-节点/Apache端口问题我使用Node/Express创建了一个小API,并试图使用Angularjs来提取数据,但是当我的html页面在localhost上Apache下运行时:8888,节点API在端口3000上侦听,我得到的是No‘Access-Control-ALL-原产地’。我尝试使用节点-http-代理和VhostApache,但没有多少成功,请参阅下面的完整错误和代码。“XMLHttpRequest无法加载localhost:3000。请求的资源上不存在”访问-控制-允许-原产地“标头。因此,不允许访问源‘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 code
angular.module('contractorsApp', [])
.controller('ContractorsCtrl', function($scope, $http,$routeParams) {
$http.get('localhost:3000').success(function(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>
3 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
// Add headersapp.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();});
哆啦的时光机
TA贡献1779条经验 获得超6个赞
router.get('/', function(req, res) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed res.setHeader('Access-Control-Allow-Credentials', true); // If needed res.send('cors problem fixed:)');});
- 3 回答
- 0 关注
- 665 浏览
添加回答
举报
0/150
提交
取消