Skip to content

Instantly share code, notes, and snippets.

@hankcouture
Created December 11, 2015 01:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hankcouture/32a0e479a8ca5de02dba to your computer and use it in GitHub Desktop.
Save hankcouture/32a0e479a8ca5de02dba to your computer and use it in GitHub Desktop.
Joke API: Builds Joke List
# Files to Ignore
node_modules
{"jokes":[]}
{
"name": "joke-api",
"version": "0.0.1",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"body-parser": "^1.14.1",
"express": "^4.13.3",
"nodemon": "^1.8.1"
},
"engines": {
"node": "5.2.x"
},
"author": "Hank Couture",
"license": "MIT"
}
var http = require("http");
var fs = require('fs');
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(bodyParser.json());
app.set('port', 3000);
app.get('/jokes', function(req, res) {
fs.readFile('./jokes.txt', function(err, jokes) {
if (err) throw err;
res.setHeader('Content-Type', "application/json");
res.end(jokes);
})
})
app.post('/jokes', function(req, res) {
var joke = req.body;
console.log('joke:', joke);
fs.readFile('./jokes.txt', function(err, jokes) {
if (err) throw err;
var jokeList = JSON.parse(jokes)
jokeList.jokes.push(joke);
console.log('jokelist:', jokeList);
jokeList = JSON.stringify(jokeList);
fs.writeFile('./jokes.txt', jokeList, function(err){
if (err) throw err;
res.end("that was a success bro. Next time, try to be funnier");
})
})
})
app.listen(app.get('port'), function(){
console.log('Node app is running on port', app.get('port'));
});
@joshuagish
Copy link

{
"q": "Why did the boy drop his ice cream?",
"a": "Because he was hit by a bus."
}

@gilbert
Copy link

gilbert commented Dec 11, 2015

Great job! It's very good that you're thinking about Content-Type. As a tip, express should set it to application/json for you when you res.send an object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment