node.js + expressでjsonを使う例
あまり例を見かけなかったので、サンプルを動かした際のやり方をメモ。
特別なライブラリが不要ってのがうれしい。
以下は、Restful APIのイメージで、あるリクエストに対してサーバー側からブラウザ側にjsonでデータを送るケース。
/** * Module dependencies. */ var express = require('express'); var app = module.exports = express.createServer(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); // Routes app.get('/', function(req, res){ res.render('index', { title: 'Express' }); }); app.get('/people.json', function(request, response) { // We want to set the content-type header so that the browser understands // the content of the response. response.contentType('application/json'); // Normally, the would probably come from a database, but we can cheat: var people = [ { name: 'Dave', location: 'Atlanta' }, { name: 'Santa Claus', location: 'North Pole' }, { name: 'Man in the Moon', location: 'The Moon' } ]; // Since the request is for a JSON representation of the people, we // should JSON serialize them. The built-in JSON.stringify() function // does that. var peopleJSON = JSON.stringify(people); // Now, we can use the response object's send method to push that string // of people JSON back to the browser in response to this request: response.send(peopleJSON); }); app.listen(3000); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
ポイントは"app.get('/people.json', function(request, response) {"から始まるブロック、ここでjsonの生成を実施しserializeを実行している。
これでnode.jsを起動させ、あとはブラウザで"http://localhost:3000/people.json"にアクセスする。
[{"name":"Dave","location":"Atlanta"},{"name":"Santa Claus","location":"North Pole"},{"name":"Man in the Moon","location":"The Moon"}]
成功!無事に値が取得できてる。