Created
December 11, 2015 01:39
-
-
Save hankcouture/32a0e479a8ca5de02dba to your computer and use it in GitHub Desktop.
Joke API: Builds Joke List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Files to Ignore | |
node_modules |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"jokes":[]} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')); | |
}); |
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
{
"q": "Why did the boy drop his ice cream?",
"a": "Because he was hit by a bus."
}