问题描述
我有一个正在运行的robot.rs后端,我的Flutter Web应用程序将其发送至该请求,但它无法通过OPTIONS响应.
I've got a backend running rocket.rs which my flutter web app sends a request to, but it can't get past the OPTIONS response.
我尝试将CORS(rocket_cors)添加到后端并具有选项响应,但它仍会发回:
I have tried adding CORS (rocket_cors) to the backend and having a options response, but it still sends back:
Error: XMLHttpRequest error.
dart:sdk_internal 124039:30 get current
packages/http/src/browser_client.dart.lib.js 214:124 <fn>
我在火箭项目中添加了以下内容:
I have added the following to my rocket project:
#[options("/")]
fn send_options<'a>(path: PathBuf) -> Response<'a> {
let mut res = Response::new();
res.set_status(Status::new(200, "No Content"));
res.adjoin_header(ContentType::Plain);
res.adjoin_raw_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.adjoin_raw_header("Access-Control-Allow-Origin", "*");
res.adjoin_raw_header("Access-Control-Allow-Credentials", "true");
res.adjoin_raw_header("Access-Control-Allow-Headers", "Content-Type");
res
我的flutter应用正在运行此请求:
And my flutter app is running this request:
Future<String> fetchData() async {
final data2 = await http.get("http://my-web-site.com").then((response) { // doesn't get past here
return response.body;
});
return data2;
}
问题:这是响应OPTION请求的正确方法吗?如果没有,如何在rocket.rs中实现它?
Question: Is this the proper way to respond to OPTION requests, and if not, how can I implement it in rocket.rs?
推荐答案
Lambda Fairy的评论为我解答了.
我将其全部放入GET
处理程序:
Lambda Fairy's comment answered it for me.
I put it all in the GET
Handler:
#[get("/")]
fn get_handler<'a>() -> Response<'a> {
let mut res = Response::new();
res.set_status(Status::new(200, "No Content"));
res.adjoin_header(ContentType::Plain);
res.adjoin_raw_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.adjoin_raw_header("Access-Control-Allow-Origin", "*");
res.adjoin_raw_header("Access-Control-Allow-Credentials", "true");
res.adjoin_raw_header("Access-Control-Allow-Headers", "Content-Type");
res.set_sized_body(Cursor::new("Response"));
res
这篇关于如何为Rocket.rs设置CORS或OPTIONS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!