What is difference, ruby HTTParty and angular $http - ruby-on-rails

HTTParty
url = "https://my-url/locomotive/api/tokens.json"
response = HTTParty.post(url, body: { :api_key => #api_key })
On the server:
Started POST "/locomotive/api/tokens.json" for 202.4.224.66 at 2014-06-15 17:59:57 +1000
Processing by Locomotive::Api::TokensController#create as JSON
Parameters: {"api_key"=>"5fcfe580e42944c896a49469c30aa97a384b497d"}
$http
$http({
url: 'https://ernie-locomotive.12wbt.com/locomotive/api/tokens.json',
method: 'POST',
params: data
});
Started OPTIONS "/locomotive/api/tokens.json?api_key=5fcfe580e42944c896a49469c30aa97a384b497d" for 59.167.21.65 at 2014-06-15 17:53:43 +1000
Processing by Locomotive::Public::PagesController#show as JSON
Parameters: {"api_key"=>"5fcfe580e42944c896a49469c30aa97a384b497d", "path"=>"locomotive/api/tokens"}
WARNING: Can't verify CSRF token authenticity
Basically, I thought they are two same methods. Seems that $http doesn't pass http method. HTTParty does what it requers and grabs the results correctly.

Because it is cross origin request, browser sends CORS preflight request before actual one...
More about CORS: http://www.html5rocks.com/en/tutorials/cors/

Related

#<RestClient::NotFound: 404 Not Found> error + rest-client gem

I'm getting the below error for rest-client gem while file uploading. Gem is installed properly.
require 'rest-client'
class SimpleService
include RestClient
// other methods //
def update_request method, opts ={}
headers = set_request_header
payload = opts
url = #base_uri + url_path(method)
begin
# RestClient.put url, payload, headers
RestClient::Request.execute(method: :put, url: url,
payload: payload, headers: headers)
rescue RestClient::ExceptionWithResponse => e
byebug
e.response
end
end
end
parameters for the rest client is
headers is {"Authorization"=>"ApiKey SHctT2tSNE94Ijp0cnVlfQ.4ylSKUJurtqCqfiNcm2vRROyHyWjJxWi0WFLsABLY74", "content_type"=>"json"}
url is "https://sandbox.test-simplexcc.com/v2/users/604776/kyc"
payload is <ActionController::Parameters {"identity_kyc_docunt_1"=>#<ActionDispatch::Http::UploadedFile:0x007fe2183a6d10 #tempfile=#<Tempfile:/var/folders/95/z56d5kd10_sb7s82b982fpjw0000gn/T/RackMultipart20180628-1288-1oncnou.png>, #original_filename="35155-6-adventure-time-picture.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"identity_kyc_docunt_1\"; filename=\"35155-6-adventure-time-picture.png\"\r\nContent-Type: image/png\r\n">, "controller"=>"simplex", "action"=>"update_kyc"} permitted: true>
I'm using the postman client call my rest end points. for every request im getting the same error.
(byebug) e
#<RestClient::NotFound: 404 Not Found>
I tried other rest client gem calls to invoke the endpoints. for everything i'm getting the same error.
Thanks
Ajith
I had to convert the payload to json and it solved the problem.
RestClient::Request.execute(method: :put, url: url,
payload: payload.to_json, headers: headers)

Respond with script from a Rails API app with limited middleware (config.api_only = true)?

I have a Rails 5 app build as an api app. So by default it only responds with json.
But for one specific request I need the app to respond with a script.
In a regular Rails app I would simply put my script in a js.erb file. This won't work here.
If my controller action looks like this:
def respond_with_js
end
and I request the app like this:
$.getScript("https://myapp.example.com/respond_with_js");
it responds with 204 No Content:
Started GET "/respond_with_js" for 127.0.0.1 at 2018-06-27 20:28:44 +0200
Processing by ApplicationController#respond_with_js as */*
Completed 204 No Content in 0ms
How do I work around this?
You cannot request as script, if rails server is only api version.
Rails by default responds json.
def respond_with_json
render json: {message: "works"}, status: :ok
end
To request it, you need to request as json dataType:
$.ajax({
url: "https://myapp.example.com/respond_with_json",
method: "GET",
dataType: "json",
success: function(res){
console.log(res.message)
}
})

Rails RestClient POST request failing with "400 Bad Request"

Looking at the docs there aren't any good examples of how to make a POST request. I need to make a POST request with a auth_token parameter and get a response back:
response = RestClient::Request.execute(method: :post,
url: 'http://api.example.com/starthere',
payload: '{"auth_token" : "my_token"}',
headers: {"Content-Type" => "text/plain"}
)
400 bad request error:
RestClient::BadRequest: 400 Bad Request
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/abstract_response.rb:74:in `return!'
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/request.rb:495:in `process_result'
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/me/request.rb:421:in `block in transmit'
Any good examples how to make a POST request using RestClient?
EDIT:
This is how I make the request in the model:
def start
response = RestClient::Request.execute(method: :post,
url: 'http://api.example.com/starthere',
payload: '{"auth_token" : "my_token"}',
headers: {"Content-Type" => "text/plain"}
)
puts response
end
Try using a hash like this:
def start
url= 'http://api.example.com/starthere'
params = {auth_token: 'my_token'}.to_json
response = RestClient.post url, params
puts response
end
If you just want to replicate the curl request:
response = RestClient::Request.execute(method: :post, url: 'http://api.example.com/starthere', payload: {"auth_token" => "my_token"})
Both Curl and RestClient defaults to the same content type (application/x-www-form-urlencoded) when posting data the this format.
In case you land here having the same Issue, Just know that this is a common error that happens when your environment variables are not "set".
I put this in quotes because you might have set it but not available in the current terminal session!
You can check if the ENV KEY is available with:
printenv <yourenvkey>
if you get nothing then it means you need to re-add it or just put it in your bash files
FYI: Putting my ENV variables in my ~/.bash_profile fixed it

Additional quotes in parameters

i'm trying to learn simple stuff a make HTTP request to rails app.
the problem is, when i try to make HTTP post request to my rails app, code is :
uri = URI.parse("http://localhost:4000/posts")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data( :post=> {"name" => "My query", "title" => "50"} )
response = http.request(request)
when i look into console for incoming post request, the output is:
Started POST "/posts" for 127.0.0.1 at 2015-02-02 16:14:12 +0100
Processing by PostsController#create as */*
Parameters: {"post"=>"{\"name\"=>\"My query\", \"title\"=>\"50\"}"}
Completed 500 Internal Server Error in 1ms
NoMethodError (undefined method `permit' for "{\"name\"=>\"My query\", \"title\"=>\"50\"}":String):
app/controllers/posts_controller.rb:72:in `post_params'
app/controllers/posts_controller.rb:27:in `create'
Look closely on parameters. Why does ist add additional quotation marks? how to fix this problem?
Because you are sending a stringified JSON object. I don't know what set_form_data is doing but you should be converting your request .to_json.
Look at this so question for reference here.

Rails Request Content-Type Seems incorrect when accessing API with AngularJS

I have a straightforward Rails 4.1.4 application and I'm trying to connect an AngularJS application on a separate host to it's API. Whilst I'm have no problem accessing it, Rails seems to think the request is HTML and ignores the Content-Type: 'application/json'
Started GET "/api/v1/locations?access_token=xxx&headers=%7B%22Content-type%22:%22application%2Fjson%22%7D" for 127.0.0.1 at 2014-09-03 17:12:11 +0100
Processing by Api::V1::LocationsController#index as HTML
Parameters: {"access_token"=>"xxx", "headers"=>"{\"Content-type\":\"application/json\"}"}
And in my NG application, I've tried a number of combinations of headers including:
app.factory('Location', ['$resource', "$localStorage",
function($resource, $localStorage){
return $resource('http://my-api.com/api/v1/locations/', {headers:{'Content-type' : 'application/json'}}, {
query: {
method: 'GET',
headers: {'Content-type': 'application/json'},
isArray: true,
dataType: 'json',
params: { access_token: $localStorage.accessToken }
}...
The response looks ok on the NG side, it's responding with JSON despite only having this in my locations controller:
class Api::V1::LocationsController < Api::V1::BaseController
doorkeeper_for :all
before_filter :authorize
respond_to :json
def index
#locations = #current_user.locations.order("created_at desc").limit(5)
respond_with #locations
end
end
I have also set (and tested unset) the cors headers.
I read somewhere that Rails won't read the content-type header if there's forward slashes in it...
Whilst this doesn't appear to be causing many issues, I do think it's interfering with Doorkeeper that's part of the application.
This wasn't a Rails problem. Turns out I needed to fiddle with some headers etc. in the NG config.
I added the following to app.js
$httpProvider.defaults.useXDomain = true;
// $httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
The second line threw an error but I've left in there for good measure.

Resources