But when I tried to use an API with react application I got an error and a message that I have CORS header missing. How can I fix this?
We are moving our API from warp to axum and in warp there was a method called reply::with_header(). Does axum has smth like this?
If you make a direct request to your application with something like curl and inspect the reponse headers, do you see an Access-Control-Allow-Origin header with the value you intended? If so, the problem may be with which headers & values you're setting (i.e., you're doing CORS wrong rather than doing axum wrong).
As for alternative ways to add headers in axum, assuming you want to set the same header & value on all responses, the approach I took in an axum server I wrote was to pass Router::layer() the following value:
use axum::http::header::{HeaderValue, ACCESS_CONTROL_ALLOW_ORIGIN};
use tower_http::set_header::response::SetResponseHeaderLayer;
SetResponseHeaderLayer::if_not_present(
ACCESS_CONTROL_ALLOW_ORIGIN,
HeaderValue::from_static("*"),
))
Note that layer() needs to be called after registering all the routes.
Alternatively, you can stick with what you've got but simplify it a little to (I'm here assuming CORS_ROUTE is a &str):