我用 yeoman 的样板代码 ( generator-gulp-angular )创建了一个 Angular 项目
现在在我的控制器中,我试图发出这样的 http 请求:
$http.get('http://food2fork.com/api/search?key='+key+'&page=1').then(function(response) {
vm.all = response.data;
});
但我不断收到此错误:
跨域请求被阻止:同源策略不允许在http://food2fork读取远程资源...(原因:CORS 标头“Access-Control-Allow-Origin”缺失)
我做了我的研究,发现我需要使用中间件属性将此访问控制添加到我的服务器,但我仍然收到错误这是我的server.js
文件
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var cors = require('cors');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
//here is where I added the middleware
var server = {
baseDir: baseDir,
middleware: function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
},
routes: routes
};
browserSync.instance = browserSync.init({
startPath: '/',
server: server,
browser: browser
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});
gulp.task('serve:dist', ['build'], function () {
browserSyncInit(conf.paths.dist);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
});
`
但是错误仍然存在,有什么帮助吗?