陷入这个问题,每次向我的 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)