Skip to content

Instantly share code, notes, and snippets.

@laurmurclar
Created September 17, 2018 06:13
Show Gist options
  • Save laurmurclar/3d171b3b33b4cc056889ff3bdfb0c5b9 to your computer and use it in GitHub Desktop.
Save laurmurclar/3d171b3b33b4cc056889ff3bdfb0c5b9 to your computer and use it in GitHub Desktop.
Simple node server for my Intercom Messenger app. Run with `node index.js`
const HTTP = require('http');
const INITIALIZE_RESPONSE = {
"canvas": {
"content": {
"components": [
{
"type": "text",
"text": "Tell us what your favourite product is!",
},
{
"type": "input",
"id": "favouriteProduct",
"placeholder": "Enter your favourite product",
"action": {
"type": "submit",
},
},
],
},
},
};
function collectRequestBody(request, callback) {
let body = '';
request.on('data', chunk => {
body += chunk.toString();
});
request.on('end', () => {
callback(JSON.parse(body));
});
}
HTTP.createServer((request, response) => {
response.setHeader('Content-Type', 'application/json');
if (request.url === '/initialize/') {
response.end(JSON.stringify(INITIALIZE_RESPONSE));
} else if (request.url === '/submit/') {
collectRequestBody(request, (requestBody) => {
response.end(JSON.stringify({
"canvas": {
"content": {
"components": [
{
"type": "text",
"text": `You said "${requestBody.input_values.favouriteProduct}" was your favourite. Thanks!`,
},
],
},
},
}));
});
} else {
response.statusCode = 404;
response.end();
}
}).listen(3000, (error) => {
if (error) {
console.log("Something went wrong", error);
return;
}
console.log("Server listening on port 3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment