Twitch POST request for OAuth2 token - node.js

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.
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.

I solved my problem. I wasn't writing data to the body.
...
req.write(data);
req.end();
});
...

Related

Node.js: Access JSON body of HTTP POST request with express

I'm making an http post request to my express web server sending dummy data as json. It correctly receives the request and can send back a json object, but for some reason it can't manage to access the post request body.
I'm using this code for express:
const express = require('express');
const app = express();
const port = 3000;
app.post('/test', (req, res) => {
console.log(req.body);
res.json({"some": "thing"});
});
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`)
});
And this is the code of the request:
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
json: {
url: "https://www.nothing.com",
name: "hello"
}
}, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.end()
As you can see I'm running this locally. The client receives a status code 200 and the json {"some": "thing"} sent by the server, but the server gets "undefined" from req.body. I tried using:
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify({
url: "https://www.nothing.com",
name: "hello"
})
instead of json directly in the request options, but to no avail. I even tried using app.use(express.json()); as someone suggested.
What is the problem?
Apparently the way I was doing the post request was not correct, I had to send the body in a separate line with req.write(), like this:
const http = require('http');
const data = JSON.stringify({ //<--- data to send as body
url: "https://www.nothing.com",
name: "hello"
});
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
})
})
req.on('error', error => {
console.error(error);
})
req.write(data); //<--- this line
req.end();
You have to add body-parser middleware http://expressjs.com/en/resources/middleware/body-parser.html
req.body empty on posts

Nodejs Receiving errro "options.hostname" property must be one of type string, undefined, or null. Received type object at validateHost

I am trying to do a post request to open permID API.
The request url is https://api.thomsonreuters.com/permid/match/file?Content-Type=multipart%2Fform-data
I have tried writing the code from scratch as well copy and past working parameters, headers, and body value from the code produced by postman.
The code I wrote is commented out.
Not sure where I am going wrong.
Thanks.
const express = require('express')
const app = express()
const request = require('request');
const cors = require('cors');
// const http = require('http');
// const https = require('https');
const util = require('util')
// Sets an initial port. We"ll use this later in our listener
const PORT = process.env.PORT || 8080;
app.use(cors());
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200
};
// Service end-point (search)
// app.get('/upload', function (req, res) {
// var options = {
// method: 'GET',
// url: 'https://api.thomsonreuters.com/permid/match/file?Content-Type=multipart%2Fform-data',
// headers: {
// 'cache-control': 'no-cache',
// 'x-openmatch-dataType': 'Organization',
// 'x-openmatch-numberOfMatchesPerRecord': '1',
// 'x-ag-access-token': '96CT8NAgnieeuiYA2YPeNMnbPMfHu4W8'
// },
// formData: {
// file: undefined
// }
// };
// request(options, function (error, response, body) {
// if (error) throw new Error(error);
// console.log(response)
// console.log(body);
// });
// });
// function dataReturned(e) {
// console.log("Success!");
// finalRes.end(e);
// }
// const server = http.createServer(app)
// server.listen(PORT, () => {
// console.log(`app started! at port ${PORT}`);
// });
var http = require("https");
var options = {
"method": "POST",
"hostname": [
"api",
"thomsonreuters",
"com"
],
"path": [
"permid",
"match",
"file"
],
"headers": {
"content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"x-openmatch-numberOfMatchesPerRecord": "1",
"x-openmatch-dataType": "Organization",
"cache-control": "no-cache",
"Postman-Token": "101e3dbe-96bf-4b1c-9fce-8dad5f4ff975"
}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
req.end();
Based on the HTTPS documentation, it looks like hostname should be a string rather than an array.
Instead of
var options = {
"method": "POST",
"hostname": [
"api",
"thomsonreuters",
"com"
],
...
try
var options = {
"method": "POST",
"hostname": "api.thomsonreuters.com",
...
``

Listen for https request, then when received send out another

I am trying to build a network of IOTs.
On my node server, I am listening for WAN/LAN HTTPS requests. Upon receipt, I would like it to send out a HTTP request to an independent IOT. I have gotten a simple example up:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
var a = https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
Can anybody guide on sending out a http POST request to http://192.168.1.137/?pin=ON1, along with the "hello world" in the above code?
The docs for http.request include a sample of how to send a POST request. Here it is modified to send the POST request you ask for.
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: '192.1681.137',
port: 80,
path: '/?pin=ON1',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
#include <http://192.168.1.137/?pin=ON1>
requesting=true
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
cout << "hello world">
var a = https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);

How to send parameters along with a POST http request in node?

This is my code I have written .
var querystring = require('querystring');
var http = require('http');
var body = querystring.stringify({
B1: 'Submit',
RollNumber: 12569
});
var request = http.request({
host: '14.139.56.15',
port: 443,
path: '/scheme12/studentresult/details.asp',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body)
}
}, function(res,err) {
if(err){
console.log(err);
}
console.log('Getting response..');
var resp = '';
res.on('data', function(data) {
resp += data;
});
res.on('end', function() {
console.log(resp);
});
res.on('error', function(err) {
winston.error(err);
});
request.write(body);
request.end();
});
It is giving me this error
Error: read ECONNRESET
I am doing this for the first time and don't know whether I am doing this right or not . You can visit the link and check it out . I need to get the data out of this form
You're trying to submit an HTTP request to a site listening on an HTTPS port (443). Change var http = require('http'); to var http = require('https'); (and the variable name to match if you like).

node.js http POST not working

I am having trouble getting my node.js server to do an http POST request to another node.js server. I am fairly certain that the problem lies with the http library or how I am using it because I can write a small HTML page that performs the POST exactly as I want.
Here is how the server receiving the POST is set up
var server = restify.createServer({
name: 'some server',
version: "1.0.0"
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.bodyParser());
server.post('/theurl/', handler.handlePost);
server.listen(config.port, function() {
console.log("starting server on port %d", server.address().port);
});
Inside the handlePost method I am doing this:
exports.handlePost = function(req, res, next) {
console.log("body: %s", JSON.stringify(req.body));
console.log("params: %s", JSON.stringify(req.params));
}
Here is the how the server that is sending the POST is doing it (this was taken directly from the node.js http docs)
var options = {
host: '127.0.0.1',
port: 8090,
path: '/theurl/',
method: 'POST'
};
var req = http.request(options, function(res) {
ses.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write("<some>xml</some>");
req.end();
When I run the POST, both req.body and req.params are undefined inside the handlePost method.
But if I put the following HTML in a browser, I can post to the service just fine.
<html>
<head>
<script>
function doPost()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://localhost:8090/theurl/",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("<some>xml</some>");
}
</script>
</head>
<body>
<button type="button" onclick="doPost()">POST data</button>
</body>
</html>
So am I doing something wrong with the node.js http library?
Well, right after I posted this I realized that one thing I was doing in the HTML version that I wasn't doing in the node.js version was setting the Content-Type on the request. If I change the options to this, it works:
var options = {
host: '127.0.0.1',
port: 8090,
path: '/theurl/',
method: 'POST',
headers: { "Content-type": "application/x-www-form-urlencoded" }
};
use the code below
var querystring = require('querystring');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
Make sure that you have added these things in your app.js file:
var bodyParser = require('body-parser'); // npm i body-parser
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

Resources