我正在尝试使用 Axios 从我的 React 应用程序向我的 Rust Rocket API 发送一个发布请求。问题是发送到 API 的第一个请求被阻止,而之后的每个请求都通过甚至返回响应数据。
这是我的 Axios 发布请求:
var headers = {
"Access-Control-Allow-Origin": 'http://localhost:8000',
"Content-Type": 'application/json'
}
axios.post("http://localhost:8000/api/register", {status: "starting"}, headers)
.then(response => {
if (response.status === 201 || response.status === 200) {
console.log("letter successfully submitted")
return response
}
throw new Error(response.error)
})
.catch(err => console.log(err.message))
这是我的 Cargo.toml 文件:
[package]
name = "back-end"
version = "0.1.0"
authors = [""]
edition = "2018"
[dependencies]
rocket = "0.4.6"
hyper = "0.11"
rocket_cors = "0.5.0-beta-2"
serde = { version = "1.0", feature = ["derive"]}
serde_json = "1.0"
serde_derive = "1.0"
[dependencies.rocket_contrib]
version = "0.4.6"
default-features = false
features = ["json"]
这是我的 Rust 代码:
#![feature(proc_macro_hygiene,decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate rocket_cors;
use rocket_contrib::json::{Json, JsonValue};
use rocket::http::Method;
use rocket::request::Form;
use rocket::response::Responder;
use rocket::{get, options, routes};
use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors, CorsOptions, Guard};
#[post("/register", format="json", data= "<register>")]
fn user_create(register: Json<Response>) -> JsonValue {
json!({
"status": "working".to_string(),
"result": null
})
}
#[options("/register")]
fn ping_options<'r, 'o: 'r>() -> impl Responder<'r> {
let cors = cors_options_all().to_cors()?;
cors.respond_owned(|guard| guard.responder(()))
}
fn cors_options_all() -> CorsOptions {
// You can also deserialize this
Default::default()
}
fn cors_options() -> CorsOptions {
//let allowed_origins = AllowedOrigins::some_exact(&["http://localhost:3000/register"]);
let all_origins = AllowedOrigins::all();
// You can also deserialize this
rocket_cors::CorsOptions {
allowed_origins: all_origins,
allowed_methods: vec![Method::Get, Method::Put, Method::Post, Method::Delete]
.into_iter()
.map(From::from)
.collect(),
allowed_headers: AllowedHeaders::all(),
allow_credentials: true,
..Default::default()
}
}
fn main() {
rocket::ignite()
.mount("/api", routes![user_create, ping_options])
.mount("/api", rocket_cors::catch_all_options_routes())
.manage(cors_options().to_cors().expect("To not fail"))
.launch();
}
最后是控制台输出和网络输出的截图:
我真的不想将我的应用程序放在服务器上,但我完全不知道如何进行此操作。我知道有一个叫做 Hyper 的东西可以设置 Rocket 的 Headers,但我不知道如何将它添加到我的应用程序中。