jok*_*4me 6 javascript xmlhttprequest http-headers
我的api调用要求我在标题中传递api键,但是我从api服务中收到错误 {"error":"2424452","message":"Invalid Api Key"}
我知道我的api密钥是有效的,因为我可以在Python中进行相同的api调用,例如:
req = requests.Session()
req.headers.update({'x-api-key': 'my-api-key', 'X-Product': 'my-product-name'})
req.get(url)
Run Code Online (Sandbox Code Playgroud)
但是在javscript中,同样的调用错误了.我相信我没有正确设置标题或什么?
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();
Run Code Online (Sandbox Code Playgroud)
*此XMLHttpRequest不是浏览器调用,而是支持XMLHttpRequest的应用程序
如果您不想显式设置多个标头,您可以使用
function setHeaders(headers){
for(let key in headers){
xhr.setRequestHeader(key, headers[key])
}
}
setHeaders({"Host":"api.domain.com","X-Requested-With":"XMLHttpRequest","contentType":"application/json"})
Run Code Online (Sandbox Code Playgroud)