沒有“訪問-控制-允許-原產地”-節點/Apache端口問題我使用Node/Express創建了一個小API,并試圖使用Angularjs來提取數據,但是當我的html頁面在localhost上Apache下運行時:8888,節點API在端口3000上偵聽,我得到的是No‘Access-Control-ALL-原產地’。我嘗試使用節點-http-代理和VhostApache,但沒有多少成功,請參閱下面的完整錯誤和代碼?!癤MLHttpRequest無法加載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 關注
- 704 瀏覽
添加回答
舉報
0/150
提交
取消