I’m trying to get an access token via a POST request from the Twitch API but my http.request is never executing (I don’t think) and I can’t figure out why…
Here is where I am:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var fs = require('fs');
var https = require('https');
var querystring = require('querystring');
var authInfo = require('./authInfo.json');
app.get('/twitch/auth', function(req, res) {
res.send("auth page");
var data = querystring.stringify({
client_id: authInfo.clientID,
client_secret: authInfo.clientSecret,
grant_type: "authorization_code",
redirect_uri: authInfo.redirectURI,
code: req.query.code,
state: 12345
});
var options = {
host: 'api.twitch.tv',
port: 443,
path: '/kraken/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
}
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
console.log(d);
});
});
req.on('error', (e) => {
console.log(e);
});
req.end();
});
app.listen(port, function() {
console.log('Point browser to: http://localhost:' + port);
});
PS I’ve omitted the some code for brevity but I get back an authorization code successfully.
You never req.write(data); to your POST request, so your request body is actually empty, invalid.
The express req doesn’t need to be terminated. While the practice of using a parameter name for a new variable isn’t recommended, it shouldn’t make a difference here.
Won’t express/chrome/browser hang when you make a request to /twitch/auth until browser time out if you don’t .send() something back to the req? Or have I got req and res messed up again…
checks open code
Ah yeah. I got req and res back to front again when dealing with Express…
I saw a require('request') in a few examples online and need to search what the best uses for the two modules would be.
I was actually playing with tmi.js for some chat features, didn’t realize that it was also could make requests to the API. If coding it all myself becomes too much to handle, I might just switch. I’m enjoying the learning experience. Thank you @BarryCarlyon
This was the problem. I figured it out last night before going to bed thanks to POSTman’s code feature. I didn’t find any examples of req.write() online and I’m a pretty big noob. heh. Thanks for the help @3ventic
Is there a good naming convention for distinguishing the two? Prior to posting, I was playing around and changed it from postReq but changed it when I was scraping my code for screw ups. lol
Thanks for posting this for me jpdevjosh, I was about to pull my hair out last night! lol