【问题标题】:How to make request from JavaScript by analogy curl request如何通过类比 curl 请求从 JavaScript 发出请求
【发布时间】:2016-09-11 15:35:45
【问题描述】:

我需要从 JavaScript 发出请求,但我只知道如何使用 curl

curl https://example.com/api -u test_123: -d source=123 -d description="Aaaa Bbbb" -d email="aaaa@example.com"

我知道-d是一个POST参数,所以我可以:

fetch(`${config.baseUrl}/api/users/profile/`,
{ method: 'POST',
  data: JSON.stringify({source: 123, description: 'Aaaa Bbb', email: 'aaaa@example.com'})
})
.then(response => {
  // do something
})

如何设置-u 用户?是标题吗?

更新

我在调试模式下发出请求并得到以下输出:

> * Server auth using Basic with user 'sk_test_GAaENEsG0PBmvtHBA2g49sPy'
> > POST /v1/customers HTTP/1.1
> > Authorization: Basic c2tfdGVzdF9HQWFFTkVzRzBQQm12dEhCQTJnNDlzUHk6
> > User-Agent: curl/7.35.0
> > Host: api.stripe.com
> > Accept: */*
> > Content-Length: 94
> > Content-Type: application/x-www-form-urlencoded

所以-u 选项只是转换为base64?

【问题讨论】:

标签: javascript curl fetch isomorphic


【解决方案1】:

我不知道您正在使用的 fetch 函数,我假设它是同构的一部分。如果它支持headers 选项,您可以使用base64 编码的令牌设置Authorization 标头:

fetch(`${config.baseUrl}/api/users/profile/`,
{ method: 'POST',
  headers: {
    "Authorization": "Basic " + window.btoa("test_123:password")
  },
  data: JSON.stringify({source: 123, description: 'Aaaa Bbb', email: 'aaaa@example.com'})
})
.then(response => {
  // do something
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-02
    • 2018-08-30
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 2018-06-21
    • 2017-04-23
    相关资源
    最近更新 更多