Search code examples
javascriptnode.jshttpwebsocketapi-design

I'm trying to send a JSON object from client to server and receive a response but all the approaches I find are either inadequate or overkill


I'm in a situation where I'm not sure what is the correct way of doing this. I'm trying to take a large json file, send it to the server, process and reorder it, and then send it back to the client. I don't want to store any data in a database. I know there's the HTTP GET verb, but the amount of data I would be inputting would be longer than the max length URI. I also read that you shouldn't try to do this with a HTTP POST either.

I looked into WebSockets as well but to me it appears to be overkill. I would only need the socket for the time that it takes to do the computations, then I would close it. Also I want to share the data with only the client who sent it to me.

Does any one have recommendations as for what to do. Maybe just a push in the right direction with a few links I can read. I'm really looking for something that runs down the middle of these two methods.


Solution

  • Why don't you just use a HTTP POST request? Taken from an info box on
    https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

    > Request has body                  Yes  
    > Successful response has body      Yes  
    > Safe                              No  
    > Idempotent                        No  
    > Cacheable                         Only if freshness information is included  
    > Allowed in HTML forms             Yes  
    

    As you see, a HTTP POST request is used for sending data to the server, and if the POST request was successful, the server sends data back to the client. Perfect for your situation, I think.

    A POST request doesn't have to be used within a HTML form; you could use XHR, AJAX, the fetch API, or any other way you can find to send the server a POST request. And yes, you could send JSON data with it.

    If you need more convincing:

    When the POST request is sent via a method other than an HTML form — like via an XMLHttpRequest — the body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following functions:

    • Annotation of existing resources
    • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
    • Adding a new user through a signup modal;
    • Providing a block of data, such as the result of submitting a form, to a data-handling process;
    • Extending a database through an append operation.

    Notice that there, it said that a POST request can be used to provide a block of data to a data-handling process.

    Hope this helps you. :)