I am trying to send a post request from my React application to my Rust Rocket API using Axios. The problem is that the the first request sent to the API get's blocked while every request after that goes through and even brings back response data.
Here is my Axios post request:
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))
Here is my Cargo.toml file:
[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"]
And here is my Rust code:
#![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();
}
And finally here are screenshots of the console output and the network output:
I really don't want to put my application on a server but I am completely clueless on how to proceed with this. I am aware that there is something called Hyper that sets Headers for Rocket but I am not sure how to add it to my application.