Christopher Francisco
Christopher Francisco

Reputation: 16258

How to configure CORS on a Express Route using "cors" library

I need to enable CORS on every endpoint for POST requests that matches /api/v1/support/* path.

I'm making a POST request to /api/v1/support/graphql with credentials true, but the preflight request (the OPTIONS one) returns a 401. I'm not sure what I'm doing wrong.

This is my configuration (note that I have changed the actual domain for a dummy in this sample below):

const corsOptions = {
  origin: /mydomain\.com$/,
  credentials: true,
  maxAge: 3600
};
app.options('/api/v1/support/*', cors(corsOptions));
app.post('/api/v1/support/*', cors(corsOptions));

// graphQLRouter is an instance of express.Router()
app.use('/api/v1/support/graphql', [ fowardIP, validateTokenInCookie ], graphQLRouter);

Upvotes: 1

Views: 845

Answers (1)

Seena V P
Seena V P

Reputation: 994

Can you please try this. Setting access control also

const app = express();
const corsOptions = {
  origin(origin, callback) {
    callback(null, true);
  },
  credentials: true
};
app.use(cors(corsOptions));
var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type,token');
  next();
}
app.use(allowCrossDomain);

This may help you

Upvotes: 1

Related Questions