Saturday 15 September 2012

ruby - How can I return a response to an AngularJS $http POST to Sinatra? -



ruby - How can I return a response to an AngularJS $http POST to Sinatra? -

i able post angularjs sinatra route such "200" status.

when inspect in chrome, see request payload follows:

{"input":"testing"}

but response empty.

here how post-ing:

$http({ method: "post", url: "http://floating-beyond-3787.herokuapp.com/angular", /*url: "https://worker-aws-us-east-1.iron.io/2/projects/542c8609827e3f0005000123/tasks/webhook?code_name=botweb&oauth=loo5nc0x0e2gj838_nbkohexqm0",*/ data: {input: $scope.newchat} }) .success(function (data) { // $scope.chats.push(data); $scope.chats.push($scope.newchat) // if successful value cache? }) .error(function (data) { $scope.errors.push(data); }); }; $scope.newchat = null

chrome under request payload shows -- above.

when check logs in heroku run sinatra app, can't tell if processing request payload. , i'm not getting in response:

post '/angular' puts "params: #{params}" puts params[:input] puts @json = json.parse(request.body.read) homecoming restclient.post 'https://worker.io' {:send => params[:input]} end

my expectation is:

the sinatra app can receive payload :input it can post worker on iron.io it can homecoming in response angular js along success.

is possible , if so, how?

possibly running case request.body has been read farther chain before hitting route.

try following

request.body.rewind request_payload = json.parse request.body.read

this mutual issue encountered in sinatra if addresses issue may want set in before filter.

before request.body.rewind @request_payload = json.parse request.body.read end

also next not work json payload.

params[:input]

the params[:field] style works if content-type application/x-www-form-urlencoded allow accessing form info in traditional web application style. works pull params off parameterized route; following.

post '/angular/:data' puts params[:data] # whatever processing need in here # assume created no_errors var track problems # post if no_errors body(json({key: val, key2: val2, keyetc: valetc})) status 200 else body(({oh_snap: "an error has occurred!"}).to_json) # json(hash) or hash.to_json should both work here. status 400 # replace appropriate 4xx error here... end end

something did utilize lastly style post 'myroute/:myparam , base64 encode json payload on client side , send in url :myparam slot. bit of hack , not recommend general practice. had client application not encode json info + headers request body; viable workaround.

ruby angularjs heroku sinatra

No comments:

Post a Comment