skip to Main Content

Access to XMLHttpRequest at ‘https://discord.com/oauth2/authorize?response_type=code&redirect_uri=https%3A%2F%2Fx%2Fapi%2Fauth%2Fdiscord%2Fcallback&scope=identify%20email%20guilds.members.read%20guilds.join%20guilds&client_id=x’ (redirected from ‘x/api/auth/discord’) from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

so ya ive tried a few things to try and solve the cors issue however nothing has worked. its saying im hitting the server then redirecting to discord oauth but cors is stopping me ig idk.

everything i tried failed and this is last resort

2

Answers


  1. CORS policies are enforced by browsers to restrict web pages from making requests to servers in different domains.

    A workaround would be to set up a server-side proxy/backend server. Here is an example using NodeJS:

    const express = require('express');
    const axios = require('axios');
    const app = express();
    
    app.get('/discord/oauth', async (req, res) => {
        try {
            const response = await axios.get('https://discord.com/oauth2/authorize', {
                params: {
                    response_type: 'code',
                    redirect_uri: 'https://x/api/auth/discord/callback',
                    scope: 'identify email guilds.members.read guilds.join guilds',
                    client_id: 'YOUR_CLIENT_ID'
                }
            });
            res.send(response.data);
        } catch (error) {
            res.status(500).send('Error');
        }
    });
    
    app.listen(3000, () => {
        console.log('Server running on port 3000');
    });
    

    Then, your client-side code can make a request to http://localhost:3000/discord/oauth, and the server will forward the request to Discord.


    Another solution for development is to use the browser extension Allow CORS: Access-Control-Allow-Origin, which will unblock Cross-Origin Resource Sharing.

    Login or Signup to reply.
  2. Ok since there’s no code posted in your question I can only assume you are trying to authorize something for your app via Discords oauth. Probably something like login or for you to access some users data. First you need to understand the oauth2 flow. You have probably seen this a lot when using the internet and logging in via google or discord for example. Lets walk through a simple step by step. Since I don’t have any of your code I will just kind of post some pseudo code for examples.

    1. The authorization screen.

    This is where the user can authorize an application to use their data. This needs to be visible to the user so you cannot call this via a javascript request you need to direct the user to this screen via a link or a redirect. I usually like to do it via redirect from express as it can keep your credentials much safer. So first let setup an endpoint for you to hit. For this example I am going to use localhost as your uri but in production you will need to swap this with your website domain.

    app.get('/discord/oauth', async (req, res) => {
      try {
        const params = {
          response_type: 'code',
          redirect_uri: 'http://localhost:5000/discord/callback',
          scope: 'identify email guilds.members.read guilds.join guilds',
          client_id: 'YOUR_CLIENT_ID'
        }
    
        res.redirect(`https://discord.com/oauth2/authorize?${new URLSearchParams(params)}`)
      } catch (error) {
        console.log(error)
      }
    });
    

    Then in your client side just open this endpoint either with a link or with window.open so either <a href="http://localhost:5000/discord/oauth">Authorize App</a> or window.open("http://localhost:5000/discord/oauth"). This will direct a user to the authorization screen.

    It’s worth noting that usually there is a state parameter passed to the authorization uri as well and then saved to your server session. Then you can check that state when the callback is hit just to assure that it is actually the user hitting that callback url.

    1. The callback to your app

    Once the user authorizes you to use their information discord will redirect back to your site to the redirect uri you provided. So we will set up an endpoint to deal with that. I am just going to show you in express here. You can redirect back to your client after you get the info you want on the server side or you can just have discord redirect to your client and you can call an api endpoint with the code they send you.

    They will send you an authorization code to your callback. From there you can get access tokens to fetch whatever information you want.

    app.get('/discord/callback', async (req, res) => {
      try {
        const { code } = req.query
    
        const params = {
        'grant_type': 'authorization_code',
        'code': code,
        'redirect_uri': 'Same redirect uri that you used in your authorization call'
        }
    
        const tokenRequest = await fetch(`https://discord.com/api/oauth2/token?${new URLSearchParams(params)}`, {
          method: 'POST',
          headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
    
        const { access_token, refresh_token, token_type, expires_in, identity} = await tokenRequest.json();
    
        // Now you can get your data with the access_token
        const dataRequest = await fetch('whatever discord endpoint you want')
        const data = await dataRequest.json()
    
        // redirect back to your client after you get your data
        res.redirect("http://localhost:3000/gotData")
      } catch (error) {
        console.log(error)
      }
    });
    

    Anyway that may have been a log winded explanation of oauth2.0. But it should give you a better idea of how this is actually implemented. This is not tested code it is just off the cuff but it should be fairly accurate. You can read the documentation here to get all of the details on how to use their oauth https://discord.com/developers/docs/topics/oauth2. If you have any question which I’m sure you might hit me up in the comments below.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search