使用 Http4s 构建 Web 服务(三) - CORS CSRF

CORS

还是只使用seller那个api,也不包括任何的AUTH。直接调用一下http://localhost:8085/sellers?first_name=Tom 来观察一下responseheader。结果大概如下:

HTTP/1.1 200 OK
Date: Thu, 23 Nov 2023 08:29:44 GMT
Connection: keep-alive
Content-Type: application/json
Content-Length: 37

此时创建一个新的html页面,通过点击按钮请求这个地址,并且把结果输出出来。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTTP Request Example</title>
</head>
<body>

<h1>HTTP Request Example</h1>
<button onclick="sendRequest()">Click me to send a request</button>
<div id="result"></div>

<script>
function sendRequest() {
    var xhr = new XMLHttpRequest();

    xhr.open("GET", "http://localhost:8085/sellers?first_name=Tom", true);

    xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
            document.getElementById("result").innerHTML = "Response: " + xhr.responseText;
        } else {
            document.getElementById("result").innerHTML = "Error: " + xhr.status + " - " + xhr.statusText;
        }
    };

    xhr.onerror = function () {
        document.getElementById("result").innerHTML = "Request failed";
    };

    xhr.send();
}
</script>

</body>
</html>

快速启动一下服务器,例如使用python

python -m SimpleHTTPServer 8084

在浏览器里访问localhost:8084,并且点击按钮,结果返回了Request failed。此时查看浏览器的console,会提示CORS错误。接下来需要一些额外的配置让它允许访问,增加如下代码:

  val corsService = CORS.policy
    .withAllowOriginHost(
      Set(
        Origin.Host(Uri.Scheme.http, Uri.RegName("localhost"), Some(8084))
      )
    )
    .apply(sellerRoutes[IO].orNotFound)
    .unsafeRunSync()

把允许访问的url地址放到withAllowOriginHost里面,同时把server里面withHttpApp的参数替换一下

    EmberServerBuilder
      .default[IO]
      .withHost(ipv4"0.0.0.0")
      .withPort(port"8085")
      .withHttpApp(corsService)
      .build
      .use(_ => IO.never)
      .as(ExitCode.Success)

重新尝试一下。就不会在发生CORS的错误,并且可以得到返回的结果了。

另外此时如果直接访问http://localhost:8085/sellers?first_name=Tom 会发现response的header会多一个Vary: Origin

事实上policy里面有很多有用的配置,可以根据自己的需要来设置。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。