C. Lightner
C. Lightner

Reputation: 33

Express middleware blocked by CORS policy (hitting authorization error for preflight OPTIONS request)

When this block is not present, my API works perfectly.

When I add this block in, I get a CORS error:

Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

What am I missing?

app.use((req, res, next) => {
  try {
    if (secret !== config.secret) {
      throw new Error('Not Authorized')
    } else {
      next()
    }
  } catch (err) {
    next(err)
  }
});

Upvotes: 1

Views: 277

Answers (1)

sp00m
sp00m

Reputation: 48817

Make sure the error is not thrown if the request's method is OPTIONS:

if (req.method !== "OPTIONS" && secret !== config.secret) {
  throw ...
}

See https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.

Upvotes: 1

Related Questions