Skip to content

Instantly share code, notes, and snippets.

@mpmckenna8
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpmckenna8/f9eb2a43e470de85f0bb to your computer and use it in GitHub Desktop.
Save mpmckenna8/f9eb2a43e470de85f0bb to your computer and use it in GitHub Desktop.
Middleware fix for Node Up And Running Chp 2

In chp 2 of Node Up and Running http://chimera.labs.oreilly.com/books/1234000001808/ch02.html#I_sect12_d1e1886 ex 2-15 and the surrounding and probably some following stuff don't work properly. I think I kind of fixed it with the following fakeNoTwit.js and twTest.js files which work to make the simple server and test it a little.

Twas a simple fix. Just had to use the body-parser module because .bodyParser() was removed from the main Express module because of security flaws I guess. Have fun playing with node!

var express = require('express');
var middler = require('body-parser')
var app = express()
app.listen(8000)
app.use(middler());
var tweets = []
app.get('/', function(req, res) {
res.send('Welcome to Node Twitter')
})
app.post('/send', function(req, res) {
if (req.body && req.body.tweet) {
console.log(req.body.tweet)
tweets.push(req.body.tweet)
res.send({status:"ok", message:"Tweet received"})
} else {
//no tweet?
res.send({status:"nok", message:"No tweet received"})
}
})
app.get('/tweets', function(req,res) {
res.send(tweets)
})
var http = require('http'),
assert = require('assert')
var opts = {
host: 'localhost',
port: 8000,
path: '/send',
method: 'POST',
headers: {'content-type':'application/x-www-form-urlencoded'}
}
var req = http.request(opts, function(res) {
res.setEncoding('utf8')
var data = ""
res.on('data', function(d) {
data += d
})
res.on('end', function() {
assert.strictEqual(data, '{"status":"ok","message":"Tweet received"}')
})
})
req.write('tweet=testing')
req.end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment