0

I have to get a token from a URL for an API of "ile de France mobilité", I'm using Fetch and I don't understand how to do this. This is my actual code:

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) 

And for answer I have

'Other stuff and :'

 [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 } } 

Does someone know how to do this?

In my index.html I call this script:

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

server:

const app = express() app.listen(3000, () => console.log('listening at 3000')) app.use(express.static('public')) app.use(express.json()) app.use(bodyParser.json()) 
16
  • and my route is: app.post('/trajet', async (request, response) => Commented Oct 6, 2020 at 9:34
  • and my route is irrelevant since your code never accesses that route - is the code you posted in a browser? It would be extremely odd (and insecure) if it is Commented Oct 6, 2020 at 9:43
  • so, anyway const json = await fetch_response should be const json = await fetch_response.json() for a start Commented Oct 6, 2020 at 9:44
  • don't post code in a comment - I think you misunderstand fetch response ... if response = await fetch then it isn't a Promise ... you need to use one of the methods like .text() or .json() etc to access response data Commented Oct 6, 2020 at 9:45
  • @JaromandaX so how can i show you my Code ? Commented Oct 6, 2020 at 9:45

1 Answer 1

1

HTTP Status Code 401 Unauthorized indicates that your request lacks valid authentication credentials. So there must be a problem in your body that you are sending.

Try sending the body in this format:

body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret, 
Sign up to request clarification or add additional context in comments.

2 Comments

THANKS its working thanks men, I have a question how can I put you as an answer ?
You are most welcome. Just click on the " ✓ " grey colored symbol to accept it as the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.