Hi
I'm trying to get a test hello world type app working but I don't seem to be
able to route RPC requests to the appropriate handler.
The regular url routing works fine. I think it's probably in the way I
construct my request in javascript but I'm not sure. Here's the simplest
code demonstrating what I'm trying to achieve.
class hello : public cppcms::application {
public:
hello(cppcms::service& svc) : cppcms::application(svc) {
parse_options("VegaWeb.cfg");
dispatcher().assign("",&hello::welcome,this);
mapper().assign("");
mapper().root("/hello");
}
void welcome();
private:
};
void hello::welcome() {
VegaData::message m;
m.text = "Hello";
render("message",m);
}
class rpc : public cppcms::rpc::json_rpc_server {
public:
rpc(cppcms::service& svc) : cppcms::rpc::json_rpc_server(svc) {
bind("div",cppcms::rpc::json_method(&rpc::div,this),method_role);
};
void div(int x, int y) {
if(y == 0)
return_error("Division by 0");
else
return_result(x/y);
}
};
int main(int argc,char** argv) {
try {
cppcms::service srv(argc,argv);
srv.applications_pool().mount(cppcms::applications_factory<hello>());
srv.applications_pool().mount(cppcms::applications_factory<rpc>());
srv.run();
} catch(std::exception const &e){
std::cerr << e.what() << std::endl;
}
return 0;
}
// script.js
$(document).ready(function () {
$("#button").click(function() {
var xhr = new XMLHttpRequest();
xhr.open("post", '/rpc');
// Required by JSON-RPC over HTTP
xhr.setRequestHeader("Content-Type","application/json");
var x=2; // hardcode
var y=3;
var request = '{"method":"div","params":[' + x + ',' + y
+'],"id":1}';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var res;
if(xhr.status === 200) {
// Don't call eval in real code use some
parser
var result = eval('(' + xhr.responseText +
')');
if(result.error==null) {
res = result.result;
}
else {
res = result.error;
}
}
else {
res = 'Invalid Status ' + xhr.status;
}
document.getElementById('result').innerHTML = res;
}
}
xhr.send(request);
return false;
});
});
config.js
{
"service" : {
"api" : "http",
"port" : 8081
},
"http" : {
"script_names" : [ "/hello" ] ,
"script" : "/rpc",
},
"file_server" : {
"enable" : true,
"mime_types" : "mime.types"
}
}
|