当我在 javaScript 中使用 fetch 发出 http 请求时
在控制台中出现此错误
test.ulvhgujdfd14.repl.co/:1 Access to fetch at 'https://api.binance.com/api/v3/userDataStream' from origin 'https://test.ulvhgujdfd14.repl.co' has been blocked by CORS policy: Request header field x-mbx-apikey is not allowed by Access-Control-Allow-Headers in preflight response.
(index):24 POST https://api.binance.com/api/v3/userDataStream net::ERR_FAILED
(anonymous) @ (index):24
(index):27 error TypeError: Failed to fetch
at (index):24:5
控制台屏幕:
网络屏幕:
我的Html和JS代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
var myHeaders = new Headers();
myHeaders.append(
"X-MBX-APIKEY",
"My API HERE"
);
myHeaders.append(
"Content-Type", "text/plain"
);
var requestOptions = {
method: "POST",
headers: myHeaders,
};
fetch("https://api.binance.com/api/v3/userDataStream", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
</script>
</body>
</html>
我尝试在本地运行它
node test.js
并且有效,但是当我在服务器上运行此代码时出现此错误
API 应该返回
{"listenKey":"xOqufW2FOYW6OVpRtHv8NX47Ptgb6Czi3a9Mf7il8iMVkQqBUGMZWzLosaB8"}
您可以从服务器上托管的服务器端脚本(例如 Node.js、Python、PHP 等)发出请求,而不是直接从客户端 JavaScript 代码发出请求。然后,您的服务器可以将数据提供给您的网页。这绕过了 CORS 问题,因为请求源自与您的网页相同的域。