Server-side AJAX with Node.js+Express
These examples illustrate some simple servers built using Node.js using the widely used Express framework. (An earlier copy of this page, found here, has versions of these servers without using Express.)
0. Basic example
var express = require('express');
var app = express();
app.get('/:name', function (req, res) {
var name = req.params.name;
console.log('Requested ' + name);
res.send('<!DOCTYPE html><html lang="en"><head>'
+ '<meta charset="utf-8">'
+ '<title>' + name + '</title>'
+ '</head><body>'
+ '<h1><tt>' + name + '</tt></h1>'
+ '</body></html>');
});
app.listen(8888);
1. HTML-based communication, text file storage
For use in conjunction with “1. HTML-based communication” in the Browser-side examples.
var express = require('express');
var fs = require('fs');
var app = express();
app.use(express.logger()); // displays info for each HTTP request
app.use(express.urlencoded()); // creates req.body for POST requests
app.use(app.router);
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/forum-base.html');
});
app.get('/fetch', function (req, res) {
console.log('sending posts');
res.sendfile(__dirname + '/posts.html');
});
app.post('/addnew', function (req, res) {
console.log('posting message');
var name = req.body.name || 'Unknown';
var message = req.body.message || '(none)';
// SECURITY HOLE: confirm name and message are reasonably short
// SECURITY HOLE: escape quotes and special chars
var fileOut = fs.createWriteStream(__dirname + '/posts.html',
{ flags: 'a' });
fileOut.write('<div><b>User:</b> ' + name
+ '<br />' + message + '</div>\n');
fileOut.end();
res.sendfile(__dirname + '/forum-base.html');
});
app.listen(8888);
2. JSON-based communication, SQLite storage
For use in conjunction with “2. JSON-based communication” in the Browser-side examples.
var express = require('express');
var sqlite3 = require('sqlite3');
var app = express();
var db = new sqlite3.Database('posts.db');
function fetchMessages(res) {
db.all('SELECT name, message FROM posts', [], function (err, rows) {
if (err !== null) {
res.send({ ok: false, message: 'error while fetching' });
console.log('fetch error', err);
} else {
var posts = [];
rows.forEach(function (row) {
posts.push({ name: row.name, message: row.message });
});
res.send({ ok: true, posts: posts });
}
});
}
app.use(express.logger()); // displays info for each HTTP request
app.use(express.urlencoded()); // creates req.body for POST requests
app.use(app.router);
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/forum-base.html');
});
app.get("/fetch", function (req, res) {
console.log('doing fetch');
fetchMessages(res);
});
app.post("/addnew", function (req, res) {
console.log('doing add');
// SECURITY HOLE: confirm name and message are reasonably short
db.run('INSERT INTO posts (name, message) VALUES (?, ?)',
[req.body.name, req.body.message], function (err) {
if (err !== null) {
res.send({ ok: false, message: 'error while posting' });
console.log('post error', err);
} else {
fetchMessages(res);
}
});
});
app.listen(8888);
(Now that you have read this, I suggest reading
The async
library,
which discusses a key library that is useful for any reasonably
sophisticated Node.js program.)