【问题标题】:How do I format my headers for an API request using Javscript?如何使用 Javascript 格式化 API 请求的标头?
【发布时间】:2020-02-27 12:27:35
【问题描述】:

我正在尝试使用具有以下要求的the Discogs API:

Content-Type: application/x-www-form-urlencoded
Authorization:
        OAuth oauth_consumer_key="your_consumer_key",
        oauth_nonce="random_string_or_timestamp",
        oauth_signature="your_consumer_secret&",
        oauth_signature_method="PLAINTEXT",
        oauth_timestamp="current_timestamp",
        oauth_callback="your_callback"
User-Agent: some_user_agent

我刚刚学习 Javascript,将使用 fetch。该文档解释了如何很好地使用它 - 包括如何添加标题。我的问题是,如何格式化正确的 Discogs 要求?

这是我卡住的地方:

const discogs_headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            ...
        }

如何将以下内容添加到该词典中?

Authorization:
        OAuth oauth_consumer_key="your_consumer_key",
        oauth_nonce="random_string_or_timestamp",
        oauth_signature="your_consumer_secret&",
        oauth_signature_method="PLAINTEXT",
        oauth_timestamp="current_timestamp",
        oauth_callback="your_callback"

我试过了,但它不能正常工作:

const discogs_headers = {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": "OAuth oauth_consumer_key="your_consumer_key", oauth_nonce="random_string_or_timestamp",...
            }

注意:我实际上是在此处填写我的应用程序信息,只是出于此问题的目的使用文档条目。如果措辞不当,我深表歉意。请不要犹豫,询问是否有什么我可以添加的内容。

感谢您的宝贵时间。

【问题讨论】:

  • 它不起作用,因为它是语法错误。请注意问题本身中突出显示的语法。您正在尝试在字符串中使用 " 字符,该字符串本身由 " 字符表示。您可以将字符串包装在 ' 中:'OAuth oauth_consumer_key="your_consumer_key", ...' (当然也将值替换为您的实际值。只是不要在这里为所有人看到。)

标签: javascript oauth http-headers


【解决方案1】:

您可以像这样在Authorization 部分中使用模板文字(为简单起见)。

const consumerKey = 'your_consumer_key';
const nonce = 'random_string_or_timestamp';

// ...
const discogs_headers = {
  'Content-Type': "application/x-www-form-urlencoded",
  Authorization: `OAuth oauth_consumer_key="${consumerKey}", oauth_nonce="${nonce}"`
};

console.log(discogs_headers);

consumerKey、nonce 等显然是与您的应用相关联的值。同样,这个答案中没有填写整个 Authorization 标头,但它的要点就在那里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2020-11-07
    • 2013-04-17
    相关资源
    最近更新 更多