Skip to content

Instantly share code, notes, and snippets.

@miloandmilk
Forked from hagino3000/app.js
Last active September 9, 2022 00:22
Show Gist options
  • Select an option

  • Save miloandmilk/5853400 to your computer and use it in GitHub Desktop.

Select an option

Save miloandmilk/5853400 to your computer and use it in GitHub Desktop.
/**
* Module dependencies.
*/
var express = require('express');
var rpcMethods = require('./methods.js');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
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.redirect('test.html');
});
// RPC end point
app.post('/rpc', function(req, res) {
res.header('Content-Type', 'application/json');
// Add in support for GET requests
if(req.method === 'GET'){
var url_parts = url.parse(req.url, true);
var data = req.query;
}
else if(req.method === 'POST'){
var data = req.body;
}
else{
onError({
code: -32603,
message: 'Exception at method call',
data: e
}, 500);
}
var data = req.body, err = null, rpcMethod;
if (!err && data.jsonrpc !== '2.0') {
onError({
code: -32600,
message: 'Bad Request. JSON RPC version is invalid or missing',
data: null
}, 400);
return;
}
if (!err && !(rpcMethod = rpcMethods[data.method])) {
onError({
code: -32601,
message: 'Method not found : ' + data.method
}, 404);
return;
}
try {
rpcMethod(data.params, {
onSuccess: function(result) {
var resString = JSON.stringify(
{
jsonrpc: '2.0',
result: result,
error : null,
id: data.id
});
//handle JSONp - add this around result string
if ( req.query && req.query.callback ) {
resString = req.query.callback + '(' + resString + ');';
}
res.send(resString, 200);
},
onFailure: function(error) {
onError({
code: -32603,
message: 'Failed',
data: error
}, 500);
}
});
} catch (e) {
onError({
code: -32603,
message: 'Excaption at method call',
data: e
}, 500);
}
return;
function onError(err, statusCode) {
res.send(JSON.stringify({
jsonrpc: '2.0',
error: err,
id: data.id
}), statusCode);
}
});
// Only listen on $ node app.js
if (!module.parent) {
app.listen(3000);
console.log("Express server listening on port %d", app.address().port)
}
@miloandmilk
Copy link
Copy Markdown
Author

Added GET/JSONp support to hagino3000's nice json-rcp route.

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