6

我用 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, []);
});
`

但是错误仍然存​​在,有什么帮助吗?

4

2 回答 2

2

您需要 http-proxy-middleware 但不使用它!如果您想为所有包含 /api 的 URL 解析跨域,首先您应该将您的 Angular 请求转发到您的 BrowserSync 服务器

所以

$http.get('http://food2fork.com/api/search?key='+key+'&page=1')

应该成为

$http.get('/api/search?key='+key+'&page=1')

BrowserSync 将收到呼叫

在浏览器中,将调用中继到后面的真实服务器

target :'http://food2fork.com/'

并在响应返回时添加 Cross Origin 标头

changeOrigin: true,

完整配置变为:

var proxyMiddleware = require('http-proxy-middleware');

const jsonPlaceholderProxy = proxyMiddleware('/api', {
  target: 'http://food2fork.com/api',
  changeOrigin: true,
  logLevel: 'debug'
});

module.exports = function() {
  return {
    server: {
      middleware: [jsonPlaceholderProxy],
      baseDir:  baseDir
    }
  };
};
于 2016-12-16T02:49:44.577 回答
0

您应该在服务器端添加允许哪些标头和方法的附加信息。例如:

res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

或者

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

这将告诉服务器接受客户端发送的标头(例如 Origin)以及您计划支持的 HTTP 方法(例如 GET)。

有关 CORS 的更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

于 2016-04-28T11:20:25.643 回答