Insert header Access-Control-Allow-Origin in reply. (axum)

Hi,
I need to insert header "Access-Control-Allow-Origin" in reply in axum framework. I thought I've achieved my goal with this variant

pub fn release_headers_for_reply() -> HeaderMap {
    let mut headers = HeaderMap::new();
    headers.insert("Access-Control-Allow-Origin", CORS_ROUTE.parse().unwrap());
    return headers
}

pub fn reply_with_message<T>(condition : bool, message : T) -> (HeaderMap, Json<Message>)
    where T : Display
{
    return (release_headers_for_reply(), Json(Message {
        is_succeed: condition,
        message: message.to_string(),
    }))
}

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):

pub fn reply_with_message<T>(condition : bool, message : T) -> Response<Body>
    where T : Display
{
    (
        [("Access-Control-Allow-Origin", CORS_ROUTE)],
        Json(Message {
            is_succeed: condition,
            message: message.to_string(),
        })
    ).into_response()
}

thx for your reply, I'll give it a try!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.