javascriptnode.jstwitchnode-fetchtwitch-api

{"status":400,"message":"missing client id"} response when using node-fetch


I am trying to get an oauth token from Twitch, and with this code:

import dotenv from 'dotenv';
dotenv.config();
import fetch from 'node-fetch';

let creds = {
        client_id:process.env.CLIENT_ID,
        client_secret:process.env.CLIENT_SECRET,
        grant_type:"client_credentials"
};

let request = {
    method:'POST',
    header:{ "Content-Type": "application/json" },
    body:creds
};
console.log(request);

fetch(process.env.AUTH_URL,request)
    .then (res => res.text())
    .then (text => console.log(text))

With my secret and client id where appropriate. However it keeps returning:

{"status":400,"message":"missing client id"}

What am I doing wrong?


Solution

  • You need to stringify the body before sending it and headers instead of header.

    let request = {
        method:'POST',
        headers:{ "Content-Type": "application/json" },
        body:JSON.stringify(creds)
    };
    

    Also, maybe use res.json() instead because the return data maybe json.

    fetch(process.env.AUTH_URL,request)
        .then (res => res.json())
        .then (text => console.log(text))