小编Muh*_*jid的帖子

使用 actix-web 时缺少“Access-Control-Allow-Origin”

陷入这个问题,每次向我的 actix-web 服务器发出 POST 请求时都会收到此错误。

CORS header 'Access-Control-Allow-Origin' missing
Run Code Online (Sandbox Code Playgroud)

我的 javascript (VueJs 在 localhost:3000 上运行):

let data = //some json data
let xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/abc");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = () => {
    console.log(xhr.responseText);
}
xhr.send(JSON.stringify(data));
Run Code Online (Sandbox Code Playgroud)

我的 Actix_Web 服务器(在 localhost:8080 上运行):

#[actix_web::main]
async fn main() {

    HttpServer::new(move || {
        let cors = Cors::default()
        .allowed_origin("http://localhost:3000/")
        .allowed_methods(vec!["GET", "POST"])
        .allowed_header(actix_web::http::header::ACCEPT)
        .allowed_header(actix_web::http::header::CONTENT_TYPE)
        .max_age(3600);

        App::new()
        .wrap(cors)
        .service(myfunc)
    })
    .bind(("0.0.0.0", 8080))
    .unwrap()
    .run()
    .await
    .unwrap();

}
Run Code Online (Sandbox Code Playgroud)

我的 Cargo.toml 依赖项

[dependencies]
actix-web = "4"
actix-cors …
Run Code Online (Sandbox Code Playgroud)

http rust rust-actix actix-web

5
推荐指数
1
解决办法
1730
查看次数

标签 统计

actix-web ×1

http ×1

rust ×1

rust-actix ×1