我已经使用Node/Express创建了一个小API,并试图使用Angularjs拉数据,但由于我的html页面在localhost:8888和节点API在端口3000上监听下运行,我得到了No 'Access-Control-Allow-Origin'。我尝试使用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>
/**
* Allow cross origin to access our /public directory from any site.
* Make sure this header option is defined before defining of static path to /public directory
*/
expressApp.use('/public',function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
// Request headers you wish to allow
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// Set to true if you need the website to include cookies in the requests sent
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
/**
* Server is about set up. Now track for css/js/images request from the
* browser directly. Send static resources from "./public" directory.
*/
expressApp.use('/public', express.static(path.join(__dirname, 'public')));
If you want to set Access-Control-Allow-Origin to a specific static directory you can set the following.
另一种方法是简单地添加头到你的路由:
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:)');
});
你可以使用"$http.jsonp"
OR
下面是周围的工作铬为本地测试
你需要使用以下命令打开你的chrome浏览器。(按窗口+ R)
Chrome.exe --allow-file-access-from-files
注意:你的chrome浏览器不能打开。当你运行这个命令时,chrome浏览器会自动打开。
如果你在命令提示符中输入这个命令,然后选择你的chrome安装目录,然后使用这个命令。
下面是在MAC中使用“——allow-file-access-from-files”打开chrome的脚本代码
set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
set switch to " --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"
第二个选项
你可以使用open(1)来添加标志:open -a '谷歌Chrome'——args——allow-file-access-from-files