如何在异步模式下使用 XMLHttpRequest 设置多个标头数据? [英] How to set multiple headers data with XMLHttpRequest in async mode?

查看:48
本文介绍了如何在异步模式下使用 XMLHttpRequest 设置多个标头数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 api 调用要求我在标头中传递 api 密钥,但我从 api 服务返回错误 {"error":"2424452","message":"Invalid Api Key"}

My api call requires me to pass the api key in the headers, but I'm getting error back from the api service {"error":"2424452","message":"Invalid Api Key"}

我知道我的 api 密钥是有效的,因为我可以在 Python 中进行相同的 api 调用,例如:

I know my api key is valid as I can make the same api call in Python just fine, example:

req = requests.Session()
req.headers.update({'x-api-key': 'my-api-key', 'X-Product': 'my-product-name'})
req.get(url)

但是在 javscript 中,同样的调用出错了.我相信我没有正确设置标题还是什么?

But in javscript, the same call errors out. I believe I'm not setting the headers correctly or something?

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 的应用程序中.
    • This XMLHttpRequest is not a browser call, rather in an application that support XMLHttpRequest.
    • 推荐答案

      setRequestHeader 设置 one 标头并接受 两个 参数(名称和值).

      setRequestHeader sets one header and takes two arguments (the name and the value).

      如果要设置多个标头,则多次调用setRequestHeader.不要在第一次调用中添加额外的参数.

      If you want to set multiple headers, then call setRequestHeader multiple times. Don't add extra arguments to the first call.

      这篇关于如何在异步模式下使用 XMLHttpRequest 设置多个标头数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆