how send post request and open url in Ruby Sinatra - ruby

i am sending a post request,
and need to get result like with html form,
where we going to some url after doing request
<form action="url" method="post">
i tried this:
return response.body()
and i get only body of html page,
but i need to redirect to this page.
what right way to go to needed URL?
here my code for post request:
post '/send' do
uri = URI.parse("https://wl.walletone.com/checkout/checkout/Index")
response = Net::HTTP.post_form(uri, {
"WMI_MERCHANT_ID" => "xxx",
"WMI_PAYMENT_AMOUNT" => "10.00",
"WMI_CURRENCY_ID" => "643"
})
end

If you want to directly pass along a POST request and redirect to it, you can do
post '/send' do
redirect <your_url>, 307
end
307 is the HTTP status code to not modify the request method.
Handle a redirect response like this:
post '/send' do
# post form
redirect response['location'], 302
end

Related

how to fix bug laravel validator with Post man send API. Validator return redirect uri root path. it not errors json status 422

how to fix bug laravel validator with Post man send API. Validator return redirect uri root path. it not errors json status 422.
Laravel redirect to root on request validation error .
I have a required field in a Laravel Request Class and when that field is not present in the request, the request is redirected to root '/'.
I am sending the request via Postman.
Please add Accept: application/json in you header.
Laravel redirect validator root url "/" by it check ajax == false. if it return true, it run
If ($ this-> expectsJson ()) {
             Return new JsonResponse ($ errors, 422);
         }
I solved the problem by adding setup POST MAN in Headers:
I hope it will be useful to the next person when the validator does not work as you expect, you need to set it up like sending ajax to the routes api:
"Key" => "value"
X-Requested-With => XMLHttpRequest
Post Man need config setting some ajax
Otherwise laravel will not be able to return error code 422.
If ($ this-> expectsJson ()) {
             Return new JsonResponse ($ errors, 422);
         }
==> return false if not have "X-Requested-With" : "XMLHttpRequest" in headers POST MAN.
ajax or not ajax active other #.
sorry i do not know english.

Where can I see the http requests my browser sends

The question is:
Where can I see the http requests my browser (Chrome) sends?
Somehow I think this is a very basic question, but I just can't find a good source to get the information I need. I want to know in order to use the Pipedrive API. I need to make a http put request to this URL with a json-type body: "https://api.pipedrive.com/v1/persons/1&api_token=d32c1ca664720eefbd5db15f5d70fd9ebb95e996"
. On their api doc page they have a tool to make example calls but I only see the URL-Part, which only contains the API-key. The other data is in the body and I can't seem to set the request up right. Therefor the initial question about where to see the requests send from my browser. I could then inspect the test-api-call..
My request approach so far:
uri = URI("https://api.pipedrive.com/v1/persons/{p_id}&api_token=12345ca664720eefbd5db15f5d70fd9ebb95e996")
Net::HTTP.start(uri.host, uri.port,
:use_ssl => true,
:verify_mode => OpenSSL::SSL::VERIFY_NONE ) do |http|
request = Net::HTTP::Put.new(uri)
request.add_field('Content-Type', 'application/json')
request.body = {'name' => 'XXXXXXXX'}.to_json
response = http.request(request) # Net::HTTPResponse object
puts response.body
end
Not sure if this is what you need, but open the Developer Tools in Chrome, go to the "Network" tab and hit record, then send the request. You'll see this request, and the subsequent ones (if any) listed. Click on it and you'll be able to browse the details.
If you want to see what the data you send looks like when it's received by the server, you can try pointing your code at httpbin, which will return it back to you, like so:
$ curl -X PUT http://httpbin.org/put -d 'this is a test'
{
"args": {},
"data": "",
"files": {},
"form": {
"this is a test": ""
},
...etc...
So then examine the contents of your response and you'll see what the server received from you and can check if it's right.

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

I am able to successfully POST from AngularJS to my Sinatra route such that I get a "200" Status.
When I inspect in Chrome, I see the request payload as follows:
{"input":"testing"}
But response is empty.
Here is how I am 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 then get the value from the cache?
})
.error(function (data)
{
$scope.errors.push(data);
});
};
$scope.newChat = null
Chrome under Request Payload shows it properly -- as above.
When I check the logs in Heroku where I run my Sinatra app, I can't tell if I am properly processing the request payload. And I'm definitely not getting anything in the Response:
post '/angular' do
puts "params: #{params}"
puts params[:input]
puts #json = JSON.parse(request.body.read)
return RestClient.post 'https://worker.io' {:send => params[:input]}
end
My expectation is:
The Sinatra app can receive the payload :input
It can successfully post to my worker on iron.io
It can return something back in the Response to Angular JS along with Success.
Is this possible and if so, how?
Possibly you are running into a case where the request.body has already been read further up the chain before hitting your route.
Try the following
request.body.rewind
request_payload = JSON.parse request.body.read
This is a fairly common issue encountered in Sinatra so if this addresses your issue you may want to put it in a before filter.
before do
request.body.rewind
#request_payload = JSON.parse request.body.read
end
Also the following will not work with a JSON payload.
params[:input]
The params[:field] style works if the Content-Type is application/x-www-form-urlencoded to allow accessing form data in a traditional web application style. It also works to pull params off a parameterized route; something like the following.
post '/angular/:data'
puts params[:data]
# Do whatever processing you need in here
# assume you created a no_errors var to track problems with the
# 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 with your appropriate 4XX error here...
end
end
Something I did recently was to use this last style post 'myroute/:myparam and then Base64 encode a JSON payload on the client side and send it in the URL :myparam slot. This is a bit of a hack and is not something I would recommend as a general practice. I had a client application that could not properly encode the JSON data + headers into the request body; so this was a viable workaround.

MultiJson::LoadError: 795: unexpected token when trying to parse incoming body request

I'm losing my sanity trying to parse an incoming request on a Sinatra app.
This is my spec
payload = File.read("./spec/support/fixtures/payload.json")
post "/api/v1/verify_payload", { :payload => payload }
last_response.body.must_equal payload
where is simply spec/support/fixtures/payload.json
{"ref":"refs/heads/master"}
My route looks like
post '/verify_payload' do
params = MultiJson.load(request.body.read, symbolize_keys: true)
params[:payload]
end
And running the spec I get the following error:
MultiJson::LoadError: 795: unexpected token at 'payload=%7B%22ref%22%3A%22refs%2Fheads%2Fmaster%22%7D'
I have tried to parse the body request in different ways without luck.
How can I make the request valid JSON?
THANKS
If you want to send a JSON-encoded POST body, you have to set the Content-Type header to application/json. With Rack::Test, you should be able to do this:
post "/api/v1/verify_payload", payload, 'CONTENT_TYPE' => 'application/json'
Alternatively:
header 'Content-Type' => 'application/json'
post '/api/v1/verify_payload'
More info here: http://www.sinatrarb.com/testing.html
The problem it is that you are passing a ruby hash, that is not well formated, you should pass a json object.
Something like this, should work:
post "/api/v1/verify_payload", { :payload => payload.to_json }

Mechanize send a POST to populate data on a page

I have a site that sends a POST to populate some data on a page. I usually look at the POST in Charles Proxy and pass the parameters like so:
bot.post('https://www.google.com?', {
"parameter" => "value",
"SESSION_parameter_ID" => "value2})
However, when I look at the request in Charles it is just sending text like this:
callCount=1
page=/eplus/mao.portal?_nfpb=true&_pageLabel=pBillPayHistory&_nfls=false
httpSessionId=2GQQQj3McPh2vQzvxnFb5KM9qgfn80Sqv2L8sC16p66nvxc5yJv5!1006025334
scriptSessionId=22A83635CAD97A33C8255AC8D559FD27672
c0-scriptName=BillingService
How do I send a POST to a URL and send the request parameters as text?
That Content-Type header should be: application/x-www-form-urlencoded
So try:
bot.post url, vars, ({'Content-Type' => 'application/x-www-form-urlencoded'})

Resources