Search code examples
jqueryjsonajaxrpcjson-rpc

Error 32600: JSON-RPC Request must be an object


My request is:

var req = {"action": "UserAPI","method": "Authenticate","data": ["un","pw"],"type": "rpc", "tid": "1"}
$.post("http://localhost/myServer/RPC/ROUTER",req, function(result){
        console.log(result.responseText);
    });

Response is:

"{ "jsonrpc" : "2.0", "error" : { "code" : -32600, "message" : "JSON-RPC Request must be an object." }, "tid" : null }"

Request is already an object. What is wrong with this?


Solution

  • If the server is expecting a JSON-RPC request, then you need to format your request the way it wants.

    JSON-RPC means that the server wants a JSON string as the POST body, not form data like you are sending.

    Try this:

    var req = {
        "action": "UserAPI",
        "method": "Authenticate",
        "data": ["un","pw"],
        "type": "rpc", 
        "tid": "1"
    };
    
    $.ajax({
        url: "http://localhost/myServer/RPC/ROUTER",
        type: 'post',
        // This tells the server we are sending
        // JSON data as the payload
        contentType: 'application/json',
        // Encode the object as a JSON string
        data: JSON.stringify(req),
        // The response is JSON
        dataType: 'json',
        success: function(result){
            // This should be parsed for you, so `result` will be an object
            console.log(result);
        }
    });