【发布时间】: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