1

I have exhausted trying all the solutions given in these posts:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

How to enable cors nodejs with express?

I have tried using cors, which seemed to be the popular solution but I am still getting the following error:

Access to XMLHttpRequest at 'http://localhost:3000/email' from origin 'http://localhost:63342' has been blocked by CORS policy: Method GET' is not allowed by Access-Control-Allow-Methods in preflight response.

This is my server side (NodeJS) setup: Attempt #1(without cors module)

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors = require('cors')
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

function setupCORS(req, res, next) {
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-type,Accept,X-Access-Token,X-Key');
  res.header('Access-Control-Allow-Origin', '*');
  if (req.method === 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
}
app.all('/*', setupCORS);


app.use('/', indexRouter);
app.use('/users', usersRouter);

Attempt #2: (with 'cors' module)

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors = require('cors')
var app = express();
app.use(cors());


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

None of these worked and I don't how to fix this. I am running the server localhost and this is how I make the GET call in my Angular:

$scope.getAllCustomerEmails = function() {
        $scope.textBox= "getAllCustomerEmails";

        $http({
            method: "GET'",
            url: "http://localhost:3000/email"
        }).then(function successCallback(response) {
            //console.log("/email response: ", response);
            $scope.textBox = response;

        }, function errorCallback(response) {
            $scope.textBox = "GET Error";
        });
    };

Any help is much appreciated.

madu
  • 5,232
  • 14
  • 56
  • 96
  • 1
    Try adding `app.options('*', cors())` after your `app.use(cors())` line (or maybe even in place of that line). That’ll cause the npm cors module to handle the OPTIONS request too. Otherwise without that I I think your existing code isn’t causing the preflight OPTIONS request to get handled. (Downvote not from me.) – sideshowbarker Jun 16 '19 at 13:13
  • Thank you @sideshowbarker. Tried that but still the same issue. – madu Jun 16 '19 at 13:58

1 Answers1

3

I think this will help you...

At the root of your application parallel to package.json file, create a new file proxy.config.json

{
   "/api*": {
     "target":"http://localhost:8080", //Add Your Backend url here
     "secure":false,
     "logLevel":"debug"
   }
}

Now in your package.json file, in scripts add this to start method.

"scripts": {
    "start":"ng serve --proxy-config proxy.config.json",
    "test":"ng test"
}
  • Thx for your answer. However, with what you suggest I still have an issue. I use Angular 9 and Express.js `Access to XMLHttpRequest at 'localhost:7777/api/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.` – phenric Apr 11 '20 at 15:58