Node.js PUT or POST request to Rails 3 Server - ruby-on-rails

I'm trying to make a PUT and/or POST request from Node.js to my Rails 3 server. I am passing my parameters in the body but they are not getting turned into the params hash in the Rails controller. My code is as follows:
http = require('http');
request = require('request');
qs = require('qs');
data = qs.stringify({name: 'Aaron', points: 10});
request_opts = {
uri: 'http://localhost:3000/users/update',
method: 'PUT',
body: data
}
request(request_opts, function() { console.log(arguments) });
I put a debugger in my Rails controller and params is nil but response.body.read returns the string I have in data.
How can I make a PUT / POST request from Node.js where the parameters are compatible with Rails?

The querystring module will serialize your data as a parameter encoded form. By default rails expects a JSON serialized entity. You should use JSON.stringify instead of qs.stringify to serialize the your user into the request body. Alternatively, you can explicitly specify a content-type header of application/x-www-form-urlencoded to tell rails the type of the body you are sending.

Related

Http post request with Content-Type: application/x-www-form-urlencoded

How to sent POST request with content-type = application/x-www-form-urlencoded.
Given an access code, I am trying to get the AccessToken using POST request where I have all the information set in POST URL so i don't know what to pass as Http content in the postAysnc method.
According to another post For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:
MyVariableOne=ValueOne&MyVariableTwo=ValueTwo.
So I have similar case where my POST url has all the information as querystring, in that case I don't know what to pass as HttpContent in the postAysnc method since its a mandatory parameter
HttpClient client = new HttpClient();
StringContent queryString = new StringContent(data);
HttpResponseMessage response = await client.PostAsync(new Uri(url), queryString );
Two options:
Continue to use StringContent, but set the content type: new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded")
Instead of using StringContent, use FormUrlEncodedContent; note that this takes in a sequence of KeyValuePair<string, string> describing the values (so for example create a dictionary containing { {"MyVariableOne", "ValueOne"}, {"MyVariableTwo", "ValueTwo"} }

Proxying MultiPart form requests in Grails

I have a Grails controller that receives a DefaultMultipartHttpServletRequest like so:
def myController() {
DefaultMultipartHttpServletRequest proxyRequest = (DefaultMultipartHttpServletRequest) request
}
This controller acts as a proxy by taking pieces of this request and then resends the request to another destination.
For non-multipart requests, this worked fine, I did something like:
IProxyService service = (IProxyService) clientFactory.create()
Response response = service.doPOST(proxyRequest.getRequestBody())
Where proxyRequest.getRequestBody() contains a JSON block containing the request payload.
However, I do not know how to get this to work with multipart request payload, since the request body is no longer a simple block of JSON, but something like the following (taken from Chrome devtools):
How can I can pass this request payload through using my proxy service above, where doPost takes a String?
Have you tried
def parameterValue = request.getParameter("parameterName")
to get the parameter value?
If you see the method signatures for DefaultMultipartHttpServletRequest you will see there are methods for getting the files and other parameters separately because the request body is getting used to both upload the file and to pass in other parameters.

Send JSON data as post method from rails controller to a web service

I am trying to send some json data from my controller written in rails to a java webservice.
On form submission i take all the input fields data do some procession on it and convert it into json object using to_json.
But how can i send it to java webservice
http://localhost:8080/exim/jsonToMapService?jsonData={"key":"value"}
You can use net/http. (as #Pierre wrote, you should create a class in lib folder, and put there your function)
url = URI.parse(service_url)
headers = {"host" => URL }
req = Net::HTTP::Post.new(url.path)
req["Content-Type"] = "application/json"
req["Accept"] = "application/json"
req.body = JSON.generate(some_data)
con = Net::HTTP.new(url.host, url.port)
# ssl for https
if full_url.include?("https")
con.use_ssl = true
con.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
res = con.start {|http| http.request(req) }
To do things like this I suggest using either RestClient or Faraday. Howeve I strongly suggest not doing the HTTP call in your controller.
Using RestClient, it would look like this:
RestClient.get('http://localhost:8080/exim/jsonToMapService', { key: :value })
You should create a class to extract this logic in the lib folder for example.
As #eightbitraptor mentioned it, when performing HTTP request like above, you should avoid blocking by performing them in a background process like Delayed Job, Resque or Sideqik.

Net::HTTP.post_form cannot send parameter

Hi I'm using rails and socket.io in node.js What I'm trying to do is send a param in rails model using Net::HTTP.post_form and get the param in node.js file which is server.js
model send.rb
def self.push(userid)
url = "http://socket.mydomain.com/push"
res = Net::HTTP.post_form(URI.parse(URI.encode(url)),data)
end
server.js
app.post('/push', function (req, res) {
console.log(req.param.userid)
});
req variable
req.ip =127.0.0.1
req.protocol= http
req.path = /push
req.host = socket.mydomain.com
req.param
I printed all the values but param always empty is there any solution for this? thanks in advance! :D
In Express you can retrieve values posted (HTTP POST) in an HTML form via req.body.searchText if you issue use app.use(express.bodyParser()); Notice that HTML form values come in req.body, not req.params.
Having said that, I am not sure how these values are submitted to the server when you use Socket.io rather than a "normal" HTTP POST on an HTML form.
I realize this is not an exact answer to your question, but wanted to mention how "normal" HTML form values are handled in case it helps and this was way to long to include as a comment.

Ruby - how to get parameters if the request is a post that sends in JSON

I have this request that comes in like this:
Parameters: {"kpi"=>{"action"=>"create", "users"=>[{"las_name"=>"Doe", "user_id"=>"123", "first_name"=>"John"}, {"las_name"=>"Smith", "user_id"=>"456", "first_name"=>"Anna"}, {"user_id"=>"789", "last_name"=>"Jones", "first_name"=>"Peter"}], "controller"=>"api/kpis"}, "users"=>[{"las_name"=>"Doe", "user_id"=>"123", "first_name"=>"John"}, {"las_name"=>"Smith", "user_id"=>"456", "first_name"=>"Anna"}, {"user_id"=>"789", "last_name"=>"Jones", "first_name"=>"Peter"}]}
but it comes as JSON in a POST request so I am not sure how to get it into a local variable.
Any idea how to do that?
Thanks!
The fact that the parameters are showing up like that means that your create action is properly set up to handle JSON as a transport mechanism. Based on that snippet, you can access these parameters via the params hash.
kpi = params[:kpi]
#users = kpi["users"]

Resources