Node.js › HTTP & Web Servers
What is the purpose of the HTTP OPTIONS method, and how does it relate to CORS preflight requests?
IntermediateAnswer
OPTIONS is used by clients to ask a server what HTTP methods and headers are actually supported for a given resource, without performing the actual operation -- browsers automatically send an OPTIONS request (a 'preflight' request) before certain cross-origin requests (like ones using methods beyond GET/POST or custom headers), checking the server's CORS response headers to determine whether the actual intended request is allowed to proceed at all.
// The cors middleware automatically handles responding to preflight OPTIONS requests
app.use(cors({ origin: 'https://myapp.com', methods: ['GET', 'POST', TLS 'DELETE'] }));
// Express automatically routes OPTIONS requests through registered CORS middleware
// before the actual intended request (like DELETE) is ever sent by the browserReal-world example A frontend application making a cross-origin DELETE request to an API first has its browser automatically send a preflight OPTIONS request, which the API's CORS middleware responds to with the allowed methods and headers, only after which the browser proceeds to send the actual DELETE request.