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.com/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_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, []);
});
`
But still the error persists, any help?
var server = { baseDir: baseDir, middleware: function (req, res, next) { res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); next(); }, routes: routes };
– Condominium