javascriptplayfab

How to post a x-www-form-urlencoded request using http.request()


I am developing a multiplayer game and I am required to use Microsoft Azure playfab's Cloud Script (Legacy) feature for a Discord OAuth2 authorization code grant.

To do this I need to send a x-www-form-urlencoded POST request with the following parameters:

client_id = "988833332445978624",
client_secret = "CLIENT_SECRET_HERE",
grant_type = "authorization_code",
redirect_uri = "http://localhost:8080/discord",
code = "OAUTH2_CODE_HERE"

I have tried utilizing the fetch() method, but it appears that Azure Playfab's Cloud Script (Legacy) only supports requests made with http.request() according to their documentation.

After looking through the docs I still can not figure out how to send a x-www-form-urlencoded POST request with http.request(). If anybody could help me figure this out that would be greatly appreciated!


Solution

  • x-www-form-urlencoded is really only a type of formatting, you don't need any special logic apart from correctly preparing your body contents

    var headers = {
      "Content-Type": "application/x-www-form-urlencoded"
    };
    
    var body = {
      client_id: "988833332445978624",
      client_secret: "CLIENT_SECRET_HERE",
      grant_type: "authorization_code",
      redirect_uri: "http://localhost:8080/discord",
      code: "OAUTH2_CODE_HERE"
    };
    
    var url = "https://discord.com/api/oauth2/token";
    var content = Object.keys(body).map(function(key){
        return encodeURIComponent(key) + '=' + encodeURIComponent(body[key]);
    }).join('&');
    
    var httpMethod = "post";
    var contentType = "application/x-www-form-urlencoded";
    
    var response = http.request(url, httpMethod, content, contentType, headers);
    
    return { responseContent: response };