首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dart HttpServer HttpResponse重定向

Dart HttpServer HttpResponse重定向
EN

Stack Overflow用户
提问于 2021-05-11 00:59:45
回答 1查看 44关注 0票数 0

我正在使用dart:io的HttpServer来实现一个web服务器,并且在使用JavaScript发送一个DELETE请求之后,我正在尝试重定向到一个页面。下面是我正在尝试做的一个最小的例子,但我不能让它正常工作。目前,当我访问localhost:8000时,下面成功地返回了主页,它也成功地返回了GET /thing中的表单按钮。当我单击delete按钮时,会成功发送一个删除/thing的请求,并返回302状态代码。然后,如预期的那样向/deleted发出请求,但该方法是DELETE,并且返回字符串“delete thing,delete method”,但不呈现该字符串。首先,我想知道如何确保重定向使用GET not DELETE (即,它应该是GET /deleted),然后我想知道如何确保"get DELETE“被渲染(假设解决前者不能解决这个问题)。我不确定问题出在Dart代码还是Javascript中。Dart .redirect()方法没有提供更改方法的方法,而且据我所知,Javascript的fetch()也不提供更改方法的方法,因此我不知道如何确保重定向使用GET而不是DELETE。

代码语言:javascript
复制
import 'dart:io';

Future<void> main() async {
  HttpServer server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8000);

  // assert(app.server != null);
  await for (HttpRequest request in server) {
    String path = request.uri.path;
    String method = request.method;

    if (path == "/" && method == "GET") {
      print("get home");
      request.response.write('home page');
      await request.response.close();
    }
    if (path == "/" && method == 'DELETE') {
      print("delete home");
      request.response.write('home page, with delete method');
      await request.response.close();
    }
    if (path == "/thing" && method == "GET") {
      print("get thing");
      request.response.headers.contentType = ContentType.html;
      request.response.write(
          """<form action="/thing"><input type="submit" value="delete"></form>
            <script>
              const form = document.querySelector("form");
              form.addEventListener("submit", event => {
                event.preventDefault();
                fetch("/thing", { method: "DELETE", redirect: 'follow'}).then(response => 
                alert("deleted thing"));
              });
            </script>""");
    }
    if (path == "/thing" && method == "DELETE") {
      print("delete thing");
      await request.response.redirect(Uri(
          scheme: request.requestedUri.scheme,
          host: request.requestedUri.host,
          port: request.requestedUri.port,
          path: "/deleted"));
    }
    if (path == "/deleted" && method == "GET") {
      print("get deleted");
      request.response.write('deleted thing');
      await request.response.close();
    }
    await request.response.close();
  }
}
EN

回答 1

Stack Overflow用户

发布于 2021-05-11 08:26:43

使用303而不是302将确保重定向是GET请求而不是DELETE请求,然而事实证明,由于https://github.com/whatwg/fetch/issues/763的原因,不可能从javascript发出重定向的HTTP请求。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67474675

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档