CORS
還是只使用seller那個api伴郁,也不包括任何的AUTH婆廊。直接調(diào)用一下http://localhost:8085/sellers?first_name=Tom
來觀察一下response
的header
宴杀。結(jié)果大概如下:
HTTP/1.1 200 OK
Date: Thu, 23 Nov 2023 08:29:44 GMT
Connection: keep-alive
Content-Type: application/json
Content-Length: 37
此時創(chuàng)建一個新的html頁面,通過點擊按鈕請求這個地址薛训,并且把結(jié)果輸出出來盆佣。
<!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>
快速啟動一下服務(wù)器,例如使用python
python -m SimpleHTTPServer 8084
在瀏覽器里訪問localhost:8084
陨舱,并且點擊按鈕翠拣,結(jié)果返回了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的參數(shù)替換一下
EmberServerBuilder
.default[IO]
.withHost(ipv4"0.0.0.0")
.withPort(port"8085")
.withHttpApp(corsService)
.build
.use(_ => IO.never)
.as(ExitCode.Success)
重新嘗試一下谜慌。就不會在發(fā)生CORS的錯誤,并且可以得到返回的結(jié)果了莺奔。
另外此時如果直接訪問http://localhost:8085/sellers?first_name=Tom
會發(fā)現(xiàn)response的header會多一個Vary: Origin
事實上policy里面有很多有用的配置畦娄,可以根據(jù)自己的需要來設(shè)置。