igrigorik / em-http-request

Asynchronous HTTP Client (EventMachine + Ruby)
1.22k stars 220 forks source link

support to send response to client ? #325

Closed ashwintastic closed 6 years ago

ashwintastic commented 6 years ago
resp = EM::HttpRequest.new('https://jsonplaceholder.typicode.com/posts/1')
  http = resp.get
  http.callback do |r|
  #send_data  or response to client">>>response is: #{r.response}" not receiving response on postman
end

I'm calling this code from postman but not getting any response there

igrigorik commented 6 years ago

That's not the correct request/response flow. If you want to send data to the endpoint, you must pass the data either as a request body, or as part of the query string. Both of those must be provided before the callback.. the callback is what's fires once you get the response back from the server.

E.g. https://github.com/igrigorik/em-http-request/wiki/Issuing-Requests#posting-data

ashwintastic commented 6 years ago

the callback is what's fires once you get the response back from the server. I want to send response which I get from server to the client

igrigorik commented 6 years ago

You already have the response.

      http.callback {
        p http.response_header.status
        p http.response_header
        p http.response
      }
ashwintastic commented 6 years ago

yes it is only printing the response but I'm not getting anything in the postman also the request/response cycle does not ends

Below code is sending response to postman resp.send_response is sending response to client

class Handler  < EventMachine::Connection
        include EventMachine::HttpServer

    def process_http_request
        resp = EventMachine::DelegatedHttpResponse.new( self )
        sleep 2 # Simulate a long running request
        resp.status = 200
        resp.content = "Hello World!"
        resp.send_response # this is sending response to postman 
  end
 end

EventMachine::run {
   EventMachine::start_server("0.0.0.0", 8080, Handler)
     puts "Listening..."
 }