javascript - Enable Cors in GulpBrowserSync - Stack Overflow

I've created an Angular project with yeoman's boilerplate code (generator-gulp-angular)And no

I've created an Angular project with yeoman's boilerplate code (generator-gulp-angular)

And now in my controller I'm trying to make a http request like this:

$http.get('='+key+'&page=1').then(function(response) {
    vm.all = response.data;
});

But I keep getting this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://food2fork... (Reason: CORS header 'Access-Control-Allow-Origin' missing)

I did my research and found I needed to add this Access Control to my server, using the middleware property, which I did, but I still keep getting an error here is my server.js file

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_ponents': 'bower_ponents'
    };
  }

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

But still the error persists, any help?

I've created an Angular project with yeoman's boilerplate code (generator-gulp-angular)

And now in my controller I'm trying to make a http request like this:

$http.get('http://food2fork./api/search?key='+key+'&page=1').then(function(response) {
    vm.all = response.data;
});

But I keep getting this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://food2fork... (Reason: CORS header 'Access-Control-Allow-Origin' missing)

I did my research and found I needed to add this Access Control to my server, using the middleware property, which I did, but I still keep getting an error here is my server.js file

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_ponents': 'bower_ponents'
    };
  }

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

But still the error persists, any help?

Share Improve this question edited Dec 15, 2016 at 13:48 Alexandre Neukirchen 2,7837 gold badges28 silver badges36 bronze badges asked Apr 28, 2016 at 10:56 Dwight LisperDwight Lisper 4755 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

You are requiring http-proxy-middleware but not using it ! If You want to resolve Cross Origin for all URL containing /api, first you should forward your Angular requests to your BrowserSync Server

So

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

Should bee

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

The BrowserSync will receive the call

In Browser relay the call to the real server in the back with

target :'http://food2fork./'

and add Cross Origin headers when the response es back with

changeOrigin: true,

the full config bees :

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

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

module.exports = function() {
  return {
    server: {
      middleware: [jsonPlaceholderProxy],
      baseDir:  baseDir
    }
  };
};

You should add additional information on the server side which headers and methods are allowed. For example:

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

or

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

This will tell the server to accept the headers send by the client (e.g. Origin) as well as the HTTP methods which you plan to support (e.g. GET).

For further informations on CORS see https://developer.mozilla/en-US/docs/Web/HTTP/Access_control_CORS

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744805074a4594725.html

相关推荐

  • javascript - Enable Cors in GulpBrowserSync - Stack Overflow

    I've created an Angular project with yeoman's boilerplate code (generator-gulp-angular)And no

    2天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信