No 'Access-Control-Allow-Origin' header is present on the requested resource nodejs

4015 views javascript
5

Access to Image at 'https://s3.us-east-2.amazonaws.com/s3bucket/1_1.png' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This is the error message I'm getting. My code works in firefox, I'm guessing firefox doesn't care about cors but in other browsers I am getting this error. I tried various things and still can't get it to work. From what I read I am supposed to add 'Access-Control-Allow-Origin': '*' to the header, tried it and it didn't work, may have done it incorrectly, not sure. I also installed the cors package and tried using that with no luck.

server.js

var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var AWS = require('aws-sdk');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


var dbHost = 'mongodb://mlab info'


mongoose.connect(dbHost, { useNewUrlParser: true })

app.get('/', function(req, res) {
        res.sendFile(__dirname + 'index.html');
}); 

//One of the things I tried
app.all('/*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
  next();
});

app.listen(process.env.PORT || 3000);

console.log('Magic happens on port 3000');

exports = module.exports = app;

ang.js

var myapp = angular.module('StarterApp', ['ngRoute','ngAnimate','ngMaterial','LocalStorageModule','ngGeolocation','md.data.table',]);
    myapp.config(['$routeProvider',
      function($routeProvider) {
        $routeProvider.
          when('/', {
            templateUrl: 'home.html',
            controller: 'mainController'
          }).
          when('/dashboard', {
            templateUrl: 'dashboard.html',
            controller: 'dashController'
          }).
          when('/kpi', {
            templateUrl: 'kpi.html',
            controller: 'kpiController'
          }).
          when('/kpiJobCreate', {
            templateUrl: 'kpiJobCreate.html',
            controller: 'bookController'
          }).
          when('/detail', {
            templateUrl: 'detail.html',
            controller: 'detailController'
          }).
          when('/book', {
            templateUrl: 'book.html',
            controller: 'bookController'
          }).
          when('/map', {
            templateUrl: 'map.html',
            controller: 'dashController'
          }).
          otherwise({
            redirectTo: '/'
          });
      }]);

      myapp.factory('userfactory', function(){
          userinfo = { };

          return {
              set: function(data){
                  userinfo = data;

              },
              get: function(){
                  return userinfo;
              }
          }
      });

dashboard.js //where I am trying to access the file. It's in a $compile template if that matters

myapp.controller("dashController", dashController);

    function dashController($scope, $http, $mdSidenav, $location, $mdDialog, $q, $timeout, $log, userfactory, localStorageService, $geolocation, $window, $compile) {

    s3.listObjects({ Prefix: featureType3 }, function (err, data) {
      if (err) {
        return alert('There was an error viewing the features: ' + err.message);
      }
      data.Contents.map(function (photo) {
        var photoKey = photo.Key;
        var photoUrl = href + encodeURIComponent(photoKey);

        var idxDot = photoKey.lastIndexOf("_") + 1;
        var extFile = photoKey.substr(idxDot, photoKey.length).toLowerCase();
        if (extFile == "1.png") {
          var htmlTemplate = $compile(
            '<li id="item3" class="ng-scope">' +
            '<img  src="' + photoUrl + '"ng-click="addFeature(\'' + photoKey + '\');">' +
            '</li>')($scope) //I see the image here but it wont pass as into another function when I click on it called addFeature where I add it to a canvas
          angular.element(document.getElementById('app7')).append(htmlTemplate)
        } else { };
      });
    });
}

answered question

"I'm guessing firefox doesn't care about cors" ???? that is generally not the case

That error can only come from some JavaScript attempting to load https://s3.us-east-2.amazonaws.com/s3bucket/1_1.png via AJAX (fetch() or XMLHttpRequest). Since I cannot see anything in your code attempting to do so, I'd say you haven't provided enough information.

if it works in firefox, what is the issue? Which browser does it NOT work in?

2 Answers

13

Instead of app.all() use app.use() And put it before app.get

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
  next();
});

Updated server.js

var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var AWS = require('aws-sdk');
//One of the things I tried
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
  next();
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


var dbHost = 'mongodb://mlab info'


mongoose.connect(dbHost, { useNewUrlParser: true })

app.get('/', function(req, res) {
        res.sendFile(__dirname + 'index.html');
}); 



app.listen(process.env.PORT || 3000);

console.log('Magic happens on port 3000');

exports = module.exports = app;

posted this
13

const express = require('express');
const app = express();        
var cors = require('cors');
        var corsOptions = {
        origin: '*'
       };
app.use(cors(corsOptions));

posted this

Have an answer?

JD

Please login first before posting an answer.