【问题标题】:How to get a Token API with fetch如何通过 fetch 获取 Token API
【发布时间】:2021-01-21 04:04:16
【问题描述】:

我必须从“ile de France mobilité”API 的 url 中获取令牌,我正在使用 Fetch,但我不明白如何执行此操作。这是我的实际代码:

    var client_id = "(my client_id)";
    var client_secret = "(my client_secret)";
    // var url_get = "https://traffic.api.iledefrance-mobilites.fr/v1/tr-global/estimated-timetable";
    var grant_type = 'client_credentials'
    var token_url = 'https://as.api.iledefrance-mobilites.fr/api/oauth/token'
    var scope = 'read-data'

    const options = {
        method: 'POST',
        headers: {
            'Content-Type' : 'application/x-www-form-urlencoded',   
        },
        body: {
            grant_type: grant_type,
            client_id: client_id,
            client_secret: client_secret,
            scope: scope
        }
    }
    const fetch_response = await fetch(token_url, options)
    const json = await fetch_response
    console.log(json)
    response.json(json)

我有答案

'其他东西和:'

  [Symbol(Response internals)]: {
    url: 'https://as.api.iledefrance-mobilites.fr/api/oauth/token',
    status: 401,
    statusText: 'Unauthorized',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

有人知道怎么做吗?

在我的 index.html 中,我调用了这个脚本:

async function asyncCall() {
    const api_url = `/trajet`
    const response = await fetch(api_url, {method: 'POST'})
    const json = await response
    //console.log(json)
}

asyncCall()

服务器:

const app = express()
app.listen(3000, () => console.log('listening at 3000'))
app.use(express.static('public'))
app.use(express.json())
app.use(bodyParser.json())

【问题讨论】:

  • 我的路线是:app.post('/trajet', async (request, response) =>
  • and my route is 无关紧要,因为您的代码从不访问该路由 - 您在浏览器中发布的代码是什么?如果是,那就太奇怪了(而且不安全)
  • 所以,无论如何const json = await fetch_response 应该是const json = await fetch_response.json() 开始
  • 不要在评论中发布代码-我认为您误解了fetch 响应...如果response = await fetch 那么它不是Promise ...您需要使用其中一种方法像 .text() 或 .json() 等来访问响应数据
  • @JaromandaX 我怎样才能给你看我的代码?

标签: javascript node.js api fetch


【解决方案1】:

HTTP 状态码 401 Unauthorized 表示您的请求缺少有效的身份验证凭据。所以你发送的身体肯定有问题。

尝试以这种格式发送正文:

body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret,

【讨论】:

  • 感谢它的工作,谢谢各位,我有一个问题,我该如何回答你?
  • 不客气。只需单击“✓”灰色符号即可接受它作为答案。
猜你喜欢
  • 2019-07-11
  • 2021-02-14
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
相关资源
最近更新 更多