I'm trying to test client requests and server responses for an operation that will set some data to a database. The server responds with a 400 saying there's something wrong with the fetch request.
This is the server-side code in rust, there's nothing wrong here but it's still useful for reference.
mod database;
use actix_files as fs;
use actix_web::{App, HttpResponse, HttpServer, Responder, web};
use serde::Deserialize;
#[derive(Deserialize)]
struct Info
{
operation: String,
key: String,
field: String,
value: String
}
async fn index(info: web::Json<Info>) -> impl Responder
{
let info = info.into_inner();
if info.operation == "set".to_string()
{
database::set(info.key, info.value).ok();
HttpResponse::Ok().body("Success!")
}
else if info.operation == "get".to_string()
{
let data = (database::get(info.key).ok()).unwrap();
HttpResponse::Ok().body(data)
}
else if info.operation == "hset".to_string()
{
database::hset(info.key, info.field, info.value).ok();
HttpResponse::Ok().body("Success!")
}
else if info.operation == "hget".to_string()
{
let data = database::hget(info.key, info.field).ok().unwrap();
HttpResponse::Ok().body(data)
}
else
{
HttpResponse::Ok().body("Unknown Operation")
}
}
#[actix_rt::main]
async fn main() -> std::io::Result<()>
{
HttpServer::new(||
{
App::new()
.route("/", web::post().to(index))
.service(fs::Files::new("/", "./main_page").show_files_listing().index_file("index.html"))
})
.bind("127.0.0.1:8088")?
.run()
.await
}
And this is my client-side javascript call:
main();
async function main()
{
set("value", "42");
}
async function set(key, value)
{
const data =
{
"operation": "set",
"key": key,
"field": "null",
"value": value
};
const options =
{
method:'POST',
headers:
{
'Content-Type': 'application/json'
},
body: data
};
fetch("http://localhost:8088/", options);
return "Success!";
}
Did I do something wrong in data or options? Thanks for the future help.