CORS allowed methods
Learn which HTTP methods a browser may use cross-origin, how CorsLayer allow methods works, and what happens when a method is not on the list
The origin list decides which places may call an API. The methods list decides what those places may do once they are allowed in. A frontend that only reads data needs GET. A frontend that creates notes needs POST. A frontend that edits and deletes needs PUT and DELETE too. The browser asks the server about each method before it uses it cross-origin, and the server answers with the methods it allows. In Axum, that answer is built by allow_methods on CorsLayer from the tower-http crate.
Where This Fits
The origin is the guest list. The methods list is what the guests are allowed to do inside. A guest who is on the list but tries something the list does not allow is still stopped, and the stopping happens before the real request is ever sent. This page is about writing that second list.
The Smallest Working Version
Start with a small API that has one route accepting several methods, and a layer that allows only two of them. Create a project with this Cargo.toml. The cors feature is what makes CorsLayer exist at all, so it must be switched on.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["cors"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Here is the server, split into two files so the tests later on this page can call the same application the server runs. The library file builds the router, and the main file only starts it.
use axum::{Json, Router, http::Method, routing::get};
use serde::Serialize;
use tower_http::cors::{Any, CorsLayer};
#[derive(Serialize)]
struct Message {
text: String,
}
pub fn app() -> Router {
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([Method::GET, Method::POST])
.allow_headers([axum::http::header::CONTENT_TYPE]);
Router::new()
.route("/api/data", get(api_data).post(api_data).put(api_data).delete(api_data))
.layer(cors)
}
async fn api_data() -> Json<Message> {
Json(Message {
text: "Some data".to_string(),
})
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The route accepts GET, POST, PUT, and DELETE, while the CORS list allows only GET and POST. That gap is deliberate. It shows that the CORS list and the route table are two separate things, and the page comes back to that gap below.
Run it with cargo run, then send a preflight for the allowed method. A preflight is the OPTIONS request the browser sends before a complex cross-origin request, asking whether the real request would be allowed. Curl is not a browser, so it never blocks a response for CORS reasons. That makes curl a good debugging tool, because it shows the raw headers the server sent.
curl -i -X OPTIONS \
-H "Origin: https://frontend.example.com" \
-H "Access-Control-Request-Method: GET" \
http://127.0.0.1:3000/api/data
HTTP/1.1 200 OK
access-control-allow-methods: GET,POST
access-control-allow-headers: content-type
access-control-allow-origin: *
allow: GET,HEAD,POST,PUT,DELETE
content-length: 0
The browser reads access-control-allow-methods: GET,POST, sees that GET is on the list, and sends the real request. Now send a preflight for a method that is not on the list.
curl -i -X OPTIONS \
-H "Origin: https://frontend.example.com" \
-H "Access-Control-Request-Method: PUT" \
http://127.0.0.1:3000/api/data
HTTP/1.1 200 OK
access-control-allow-methods: GET,POST
access-control-allow-headers: content-type
access-control-allow-origin: *
allow: GET,HEAD,POST,PUT,DELETE
content-length: 0
The two answers look almost identical, and the status is 200 in both cases. The difference is what the browser does with them. In the second answer, the requested method PUT is missing from the allowed list, so the browser never sends the real request and the console shows a CORS error naming the method. The failure shows up in the headers, not in the status, and the handler never runs for the refused request.
Working Setup:
If a preflight for an allowed method returns access-control-allow-methods with that method in the list, the setting works. If a preflight for another method returns the same list without it, that is also correct. The browser is the part that compares the two and decides.
Simple Requests and Preflight Requests
The browser handles cross-origin requests in two ways, depending on how complex the request is. A simple request uses only a GET, HEAD, or POST method, only a few basic headers, and a simple content type such as text/plain. The browser sends a simple request directly and then checks the response for CORS headers before letting JavaScript read it. There is no preflight for a simple request, so the methods list is checked on the response instead of in advance.
Anything more complex is a preflighted request. A PUT or DELETE method, a custom header such as Authorization, or a JSON content type makes the request complex. Before sending the real request, the browser sends an OPTIONS request, called a preflight, that asks the server whether the real request would be allowed. The preflight carries three headers. Origin says where the page making the request lives. Access-Control-Request-Method says which method the real request will use. Access-Control-Request-Headers lists the headers the real request will carry. The server answers with the CORS headers, and only then does the browser send the real request.
A beginner can think of a simple request as walking straight up to a door and showing a badge, and a preflighted request as calling ahead to ask whether the visit is allowed. The call ahead costs an extra round trip, and it happens because the visit is unusual enough that the door needs warning. CorsLayer handles both kinds of request on its own. You configure the rules once, and the layer adds the right headers to responses and answers preflight requests before they ever reach your handlers. You do not write an OPTIONS handler yourself.
The method of the preflight itself is always OPTIONS, whatever method the real request will use. That is why the route table never needs an OPTIONS route. The layer intercepts the preflight before routing, answers it, and the handler never sees it.
Reading the allow_methods Call
The configuration in the smallest example has three pieces, and the middle one is the subject of this page.
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([Method::GET, Method::POST])
.allow_headers([axum::http::header::CONTENT_TYPE]);
CorsLayer::new() creates a layer that allows nothing at all. No origins, no methods, no headers. That surprises beginners, because GET feels like it should work by default. It does not, for CORS purposes. The browser needs the server to say the method is allowed, and the default says nothing is allowed. You must list every method your frontend uses.
allow_methods sets the methods the browser may use cross-origin, and it decides the value of the Access-Control-Allow-Methods response header. It takes a list of Method values, imported from axum::http. The Method type is the http crate type for an HTTP method, and the constants Method::GET, Method::POST, Method::PUT, Method::DELETE, and Method::PATCH cover the methods a frontend normally uses. The list is written as an array, and the order inside the array does not matter. The server sends the methods back in the order they were listed, and the browser only checks whether the requested method is present.
The origin in the example is Any, which means any origin, written as a star in the response. The headers list names CONTENT_TYPE, the header that says what format a request body is in. Both settings are present because a working configuration needs all three lists, and this page keeps the other two simple so the methods list is the part the reader watches.
The List Is Sent Whole, Every Time:
The preflight answer always carries the full methods list, not just the method that was asked for. Asking about GET returns GET,POST, and asking about PUT returns the same GET,POST. The browser does the comparing. The server only publishes the list.
How the Browser Decides
The decision the browser makes has three steps, and each one is worth naming, because the error a beginner sees comes from the step that failed.
First, the browser sends the preflight with the method the real request will use. Second, the server answers 200 with the allowed methods list. Third, the browser checks whether the requested method is on that list. If it is, the real request goes out. If it is not, the real request is never sent, and the console shows an error like this.
Access to fetch at 'http://127.0.0.1:3000/api/data' from origin 'https://frontend.example.com' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
The error names the method that was refused, which tells you exactly what to add. The fix is one value in the allow_methods list, not a change to the handler and not a change to the route.
Two details of that flow catch beginners. The first is that the preflight answer is 200 even when it refuses the method. A 200 status with a missing method is still a refusal, and looking for a 4xx status when debugging a preflight wastes time. The second is that a refused preflight means the handler never runs. If the server logs show no request at all, that is not a logging failure. The browser stopped the request before it left the page.
For a simple request there is no preflight, so the check happens on the response. A simple GET from an allowed origin returns the data with the CORS headers, and the browser lets JavaScript read it. A simple POST works the same way, as long as its content type is simple. A POST with a JSON body is not simple, because its content type is application/json, so it gets a preflight first.
Allowing Any Method
When the API is public and the methods do not need restricting, every method can be allowed with Any.
use tower_http::cors::{Any, CorsLayer};
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers([axum::http::header::CONTENT_TYPE]);
A preflight to this configuration answers with access-control-allow-methods: *, where the star means any method is allowed. That is close to CorsLayer::permissive(), but not identical. permissive() also allows any origin, any header, and exposes all response headers. The manual version gives control over each piece separately, which is the point of building the configuration by hand.
Any is the right choice for a public read-and-write API that anyone may call. It is the wrong choice for an API with a login, where the methods list should name only what the frontend uses. One limit applies to the star and it is worth stating here, even though the full story belongs with credentials. A star method list never goes together with credentials such as cookies. The layer refuses to build that combination, and the server panics at startup if you try.
Calling allow_methods Twice Does Not Add Methods
Each builder call on CorsLayer overwrites the previous value for that setting, and allow_methods is no exception. Calling it twice keeps only the last list. That was checked by running a layer built with two chained calls, first [Method::GET] and then [Method::POST]. A preflight for GET and a preflight for POST both answered with the same header.
access-control-allow-methods: POST
The GET from the first call was gone entirely. The wrong code looks like this.
// Wrong - the second call replaces the first, it does not add to it
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([Method::GET])
.allow_methods([Method::POST]);
The fix is one call with the whole list.
// Right - every method the frontend uses, in one call
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([Method::GET, Method::POST]);
The same overwrite rule applies to the origin and headers lists. If a frontend suddenly stops working after a second method is added, check whether the code chained two calls instead of passing one list.
Chained allow_methods Calls Overwrite Each Other:
Every builder method on CorsLayer replaces the previous value for that setting. Chaining allow_methods twice keeps only the last list. Pass all methods in one call.
Allowing a Method Does Not Create a Route
The CORS list and the route table answer different questions. The route table decides which method and path combinations the server handles. The CORS list decides which of those combinations a browser page may use cross-origin. Allowing a method in CORS does not add a route for it, and adding a route does not allow it in CORS. Both lists must agree, or the request fails at one of the two checks.
The smallest example on this page shows the gap in one direction. The route accepts PUT and DELETE, but the CORS list allows only GET and POST. A browser page that tries PUT fails the preflight, and the handler never runs, even though the route exists. The gap can also run the other way. Take a router with only a GET route, and a CORS list that allows GET and POST.
use axum::{Json, Router, http::Method, routing::get};
use serde::Serialize;
use tower_http::cors::{Any, CorsLayer};
#[derive(Serialize)]
struct Message {
text: String,
}
pub fn app() -> Router {
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([Method::GET, Method::POST]);
Router::new()
.route("/api/data", get(api_data))
.layer(cors)
}
async fn api_data() -> Json<Message> {
Json(Message {
text: "Some data".to_string(),
})
}
A preflight for POST passes, because POST is on the CORS list. The browser sends the real POST, and the server answers 405, which means method not allowed, because no POST route exists for that path. The CORS check passed and the routing check failed, and the two failures look different. A CORS failure appears in the browser console and the handler never runs. A 405 appears as a normal response, and it means the route table is missing the method, not the CORS list.
A beginner can think of the two lists as two different doors in a row. The CORS list is the outer door, checked by the browser before the request leaves the page. The route table is the inner door, checked by the server after the request arrives. A request must pass both, and opening one door never opens the other.
A Plain Text Diagram of the Flow
The methods check runs inside the preflight, before the real request exists.
page wants a cross-origin PUT
|
v
browser sends OPTIONS preflight
with Access-Control-Request-Method: PUT
|
v
CorsLayer answers 200
with access-control-allow-methods: GET,POST
|
+-- PUT is on the list --> browser sends the real PUT
| |
| v
| handler runs, response returns
|
+-- PUT is not on the list --> browser stops here
|
v
console CORS error,
handler never runs
The diagram has one branch that never reaches the server. That branch is the whole point of the preflight. The browser asks first, and a refusal costs one extra request instead of a real request that would have been thrown away.
Testing It
Two tests cover the two outcomes of this page. Each test sends a preflight through the router with oneshot and checks the allowed methods header. The tower crate provides oneshot, which sends one mock request directly through the router without any network connection. A preflight is built by hand, with the method set to OPTIONS and the three preflight headers set, because no route in the application handles OPTIONS directly. The layer intercepts it.
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn preflight(method: &str) -> axum::response::Response {
app()
.oneshot(
Request::builder()
.method("OPTIONS")
.uri("/api/data")
.header("origin", "https://frontend.example.com")
.header("access-control-request-method", method)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn preflight_for_allowed_method_lists_it() {
let response = preflight("GET").await;
assert_eq!(response.status(), StatusCode::OK);
let allowed = response
.headers()
.get("access-control-allow-methods")
.unwrap()
.to_str()
.unwrap();
assert!(allowed.contains("GET"));
assert!(allowed.contains("POST"));
}
#[tokio::test]
async fn preflight_for_disallowed_method_does_not_list_it() {
let response = preflight("DELETE").await;
assert_eq!(response.status(), StatusCode::OK);
let allowed = response
.headers()
.get("access-control-allow-methods")
.unwrap()
.to_str()
.unwrap();
assert!(!allowed.contains("DELETE"));
}
The second test is the one that guards the behaviour beginners find hardest to believe. It asserts that the refused preflight still returns status 200. If somebody changed the layer to reject preflights with an error status, that test would fail, and the failure would be a signal that the code no longer matches how the browser actually behaves. The header is the whole answer, so the test reads the header, not just the status.
The tower crate is needed as a dev dependency.
[dev-dependencies]
tower = { version = "=0.5.3", features = ["util"] }
Run the tests with cargo test.
Common Beginner Mistakes
Forgetting a Method the Frontend Uses
// Wrong - the frontend edits notes with PUT, but PUT is missing here
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([Method::GET, Method::POST]);
The frontend reads and creates notes fine, and the edit button fails with a CORS error naming PUT. The fix is to add the method to the list. When a new feature adds a method to the frontend, the methods list is one of the places that must change with it, alongside the route and the handler.
Forgetting the cors Feature
Without features = ["cors"] on the tower-http dependency, the CorsLayer type does not exist and the import fails with a compile error saying the module could not be found. The fix is one word in Cargo.toml. If the compiler cannot find tower_http::cors, check the feature list before anything else.
A 405 Is Not a CORS Error:
A preflight that passes followed by a 405 response means the route table is missing the method, not the CORS list. A CORS failure never produces a 405, and a 405 never comes with a CORS error in the console. Read the status first, then decide which list to fix.
Adding the Method Only to the Route
A new PUT route with no change to allow_methods still fails in the browser, because the preflight is checked against the CORS list, not the route table. The route and the list must be updated together. A useful habit is to change them in the same edit, so they never drift apart.
Expecting GET to Work Without Being Listed
CorsLayer::new() allows no methods at all, including GET. A configuration that sets an origin and nothing else makes every cross-origin request fail, including simple reads. The origin list and the methods list are both required, and neither one implies the other.
Final Complete Example
Here is everything from this page put together. Four routes on one path, a methods list that covers the three methods the frontend actually uses, a named origin list, and the tests from the section above. The project layout is the one the smallest example used, with the application split into a library so the tests can call it.
use axum::{Json, Router, http::Method, routing::get};
use serde::Serialize;
use tower_http::cors::{AllowOrigin, CorsLayer};
#[derive(Serialize)]
struct Message {
text: String,
}
pub fn app() -> Router {
let cors = CorsLayer::new()
.allow_origin(AllowOrigin::list([
"https://frontend.example.com".parse::<axum::http::HeaderValue>().unwrap(),
"https://admin.example.com".parse::<axum::http::HeaderValue>().unwrap(),
]))
.allow_methods([Method::GET, Method::POST, Method::PUT])
.allow_headers([axum::http::header::AUTHORIZATION, axum::http::header::CONTENT_TYPE]);
Router::new()
.route("/api/data", get(api_data).post(api_data).put(api_data))
.layer(cors)
}
async fn api_data() -> Json<Message> {
Json(Message {
text: "Some data".to_string(),
})
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["cors"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "=0.5.3", features = ["util"] }
DELETE is missing from the final example on purpose. The frontend for this API reads, creates, and edits data, and it never deletes anything, so DELETE stays off the list. A method that nobody uses is a permission nobody needs, and leaving it off costs nothing. If a delete feature is added later, the method goes on the list in the same edit that adds the route.
Run the checks with these commands.
cargo check
cargo test
cargo run
Summary
The methods list is a second guest list, and it is checked before the real request exists. The browser asks about the method in a preflight, the server publishes the whole list in its answer, and the browser compares the two. A missing method is a refusal that still returns status 200, and the handler never runs, which is why a missing method shows up as silence in the server logs and an error in the browser console. Allowing a method never creates a route, and creating a route never allows a method, so the two lists must be changed together whenever a feature adds a way to touch the data.
The decision framework to carry forward is simple. List exactly the methods the frontend uses, and nothing else. When the console names a refused method, add that one method, not every method, and check the route table at the same time, because a method that passes the preflight still needs a route to land on. The next question after what the frontend may do is what it may carry with it, and that question is answered by the headers list.