I’ve adapted the example from the node.js website to demo how to send a POST request to discourse using node.js:
const http = require('http');
const crypto = require('crypto');
const querystring = require('querystring');
const title = crypto.randomBytes(6).toString("hex") + ' ' + crypto.randomBytes(3).toString("hex") + ' ' + crypto.randomBytes(4).toString("hex");
const raw = crypto.randomBytes(16).toString("hex") + ' ' + crypto.randomBytes(16).toString("hex") + ' ' + crypto.randomBytes(16).toString("hex");
const api_key = 'f2b43adc...';
const api_username = 'system';
var data = {
title: title,
raw: raw
};
data = JSON.stringify(data);
const options = {
hostname: 'localhost',
port: 3000,
path: '/posts',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
'Api-Key': api_key,
'Api-Username': api_username
}
};
const req = http.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
});
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();