Search code examples
javascriptnode.jsdiscord.jshttp-headersnode-fetch

Clash Royale Node Fetch with Key


Im trying to make a discord bot where if you type -cr into the chat, it takes the Arguments of the user (Being the Clash Royale Player's player tag) and would then use the package node-fetch to receive data with my specified endpoint. I am constantly running into the error of { reason: 'accessDenied', message: 'Invalid authorization' }. Im rather new to this stuff, especially API's, but im hoping to access certain data which I can decide later on (Which I know how to do). My code is :

const fetch = require('node-fetch')

module.exports = {
    name: 'clash',
    aliases: ['cr', 'clashroyale'],
    category: 'This',
    utilisation: '{prefix}clash',

    async execute(client, message) {
        var msgArgs = message.content.slice(this.name.length + 1)
        var endpoint = `/players/${msgArgs}`
        var url = `https://api.clashroyale.com/v1`

        var token = `hidingmytoken`

        fetch(url + endpoint, {
            method: 'POST',
            headers: {
                "Authorization": token
            }
        }).then(data => data.json()).then(json => {
            console.log(json)
        })
    },
};

The message parts with msgArgs and discord sides all work but fetching that clash Royale API is a big hurdle for me. The API for Clash Royale can be found here https://developer.clashroyale.com/#/documentation and Im just generally stuck on this whole concept. Im using version 2.6.6 of node-fetch so I can use the require() method which should work if that does matter. In general, how can I pass my token properly to receive that API data?


Solution

  • Since the Clash Royale API uses bearer authentication, you need to specify that it will be a bearer token.

    headers: {
      'Authorization': `Bearer ${token}`
    }