我的 api 调用要求我在 header 中传递 api key ,但我从 api 服务返回错误 {"error":"2424452","message":"Invalid Api Key"}
我知道我的 api key 是有效的,因为我可以在 Python 中进行相同的 api 调用,例如:
req = requests.Session()
req.headers.update({'x-api-key': 'my-api-key', 'X-Product': 'my-product-name'})
req.get(url)
但在 javscript 中,同样的调用会出错。我相信我没有正确设置 header 或其他东西?
var req = new XMLHttpRequest();
req.onreadystatechange=handleStateChange;
req.open("GET", "url", true);
req.setRequestHeader("Host", "api.domain.com", "x-api-key", "my-api-key", "X-Product", "my-product-name");
req.send();
- 此
XMLHttpRequest
不是浏览器调用,而是在支持XMLHttpRequest
的应用程序中调用。
最佳答案
setRequestHeader
设置一个 header 并采用两个 参数(名称和值)。
如果要设置多个header,那么多次调用setRequestHeader
。不要在第一次调用时添加额外的参数。
关于javascript - 如何在异步模式下使用 XMLHttpRequest 设置多个 header 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51132829/