'Slack OAuth HTTP Post Request returns "undefined" access token

I'm using the following code in a simple slash command app to handle OAuth for public distribution of my app:

const express = require("express");
const bodyParser = require("body-parser");
const fetch = require("node-fetch")
require('dotenv').config();

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

// App installation handling
app.get("/auth", async (req, res) => {
    if (!req.query.code) {
        console.log("Access denied!");
        return;
    }
    var data = {form: {
        client_id: process.env.SLACK_CLIENT_ID,
        client_secret: process.env.SLACK_CLIENT_SECRET,
        code: req.query.code,
        redirect_uri: "https://6c0c-35-20-201-50.ngrok.io/auth"
    }};
    console.log(req.query.code);

    // Send received code back to Slack and get Oauth2 access token
    const config = {
        method: "POST",
        body: data,
        headers: {'Content-type': 'application/x-www-form-urlencoded'}
    };
    console.log("We got something!");
    try {
        const slack_oauth_response = await fetch("https://slack.com/api/oauth.v2.access", config);
        console.log("Access token granted!");
        console.log(JSON.stringify(slack_oauth_response.access_token));
    } catch (e) {
        console.error(e);
    }
    res.sendStatus(200);

})

When I try using the Add to Slack button, I get a timeout error. My log results will look like this:

PS D:\Documents\SlackRegApp> node local_testing.js
1007612862405.3292595223126.481b3e25d2c29dc80af7dc21bcb84a8bc19c28ddec155a429c6651105903902f
We got something!
Access token granted!
undefined // where the access token should be

If I go ahead and just log the entirety of slack_oauth_response, it looks like this:

{"size":0, "timeout":0}

When I try to install the app via cURL, it works, like below:

curl -F code=1007612862405.3292595223126.481b3e25d2c29dc80af7dc21bcb84a8bc19c28ddec155a429c6651105903902f -F client_id=**SLACK_CLIENT_ID** -F client_secret=**SLACK_CLIENT_SECRET** https://slack.com/api/oauth.v2.access

Hoping for some help here, thanks!



Solution 1:[1]

I just used the Slack WebClient API to access the oauth.v2.access method instead of trying to make my own HTTP request.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sammie K