How would I serialize url parameters for use with axios? My parameters are just numbers in array [1,2]. Here is my code so far
axios({
method: 'delete',
url: '/api/'
})
My request url will be something like this http://127.0.0.1:8000/api/?id=1&id=2
I looked at the paramsSerializermethod that axios has but its confusing how it can be used or whether its even appropriate in my case. Please advice. Thanks
the config object of axios.get accepts params. In params you can specify your array and it will do the conversion for you.
Here is an example:
axios.get('/api/', {
params: {
id: [1,2]
}
})
This will make a request which looks like this:
/api/?id[]=1&id[]=2
Related
I am developing an API which can search the API with the given keyword in the query string parameter using HAPI JS.
For example: localhost:8000/api?search={GivenKeyWord}
Could anyone please suggest how to implement this in HAPI JS? I am using MYSQL as the Database
A code snippet of what you tried would help answer you question better. However since you mentioned you use hapi, in your handler function for this specific route you can access the query parameters with request.query, which is an object with the query parameters name as keys with their values as their value.
For what you are asking, you would probably need something like that:
server.route({
method: "GET",
path: "/api",
handler: function(request, reply) {
var searchQuery = request.query.search;
}
})
server.route({
method: "GET",
path: "/api",
handler:(request, reply) => {
let {search} = request.query;
console.log('Search param = ',search)
}
})
I would use ES6 destructuring assignment to simplify
When I have this kind of object:
myObj = {
accountNumber:"12345",
limit:"10",
offset:"0",
serviceProduced: {
min:"2015-03-01"
}
}
and I pass it via $http get as params:
$http({
url: '/foo'
method: 'GET'
params: myObj
});
for some reason it comes to server like this after its JSONified by $http:
{"accountNumber":"1191009461","limit":"10","offset":"0","serviceProduced":"{\"min\":\"2015-03-01\"}"}
How can I prevent the 'serviceProduced' not to be converted to string? So that it would be like this (correct):
{"accountNumber":"1191009461","limit":"10","offset":"0","serviceProduced":{"min":"2015-03-01"}}
I think you are miss using http get. It is not supposed to support nested objects.
It should be in the following format: ?accountNumber=1191009461&limit=10&...
However, if you want to achieve what you are looking for, you can configure your object to be like:
myObj = {
accountNumber:"12345",
limit:"10",
offset:"0",
"serviceProduced.min": "2015-03-01", // you should be able to handle this format server side.
// OR
"serviceProduced[min]": "2015-03-01"
}
try:
$http.get("#{url}", myObj)...
it should work.
I'm comunicating my Rails API with my AngularJS application.
Everything is working great and normal up until the point I have to send parameters in a GET request. This is the Rails controller
def cats
if cat_params[:color]
#cats = Cat.where(... #you know
else
//Do something else
end
private
def cat_params
params.require(:cat).permit(:color)
end
Then from Angular
var kitty = {
cat: {
color: "red"
}
}
$http.get('some URL', { params: kitty }).success.....
By this time, the params hash looks like a stringify JSON
Started GET "some URL?cat=%7B%22color%22:%22red%22%7D" for 127.0.0.1 at 2015-01-28 23:10:24 -0300
Processing by Some_controller as JSON
Parameters: {"cat"=>"{\"color\":\"red\"}", "cat_id"=>"19"}
Cat Load (0.5ms) SELECT "cat".* FROM "cats" WHERE "cat"."id" = 19 LIMIT 1
{"cat"=>"{\"color\":\"red\"}", "format"=>"json", "controller"=>"some_controller", "action"=>"some_action", "cat_id"=>"19"}
Completed 500 Internal Server Error in 95ms
NoMethodError - undefined method `permit' for "{\"cat\":\"red\"}":String:
I'm also sending the Content-Type header, set to 'application/json'.
From Angular's $http.get documentation, I read that if the value of params is something other than a string, it will stringify the JSON object, so the issue is not in the front-end.
I don't think the solution begins with starting JSON parsing the params hash, since I've had no need to do it in the past. It seems to me that strong_parameters is playing dirty, or Rails is ignoring the JSON string. Any ideas what to do next?
I just ran into the same issue. Changing the param serializer solved the issue for me:
$http.get('someURL', {
paramSerializer: '$httpParamSerializerJQLike',
params: {cat: {color: 'red}}
})
Also adding the 'Content-Type': 'application/json' header will not help since it applies to the the body the request.
I used to meet a $http.get problem that when call $http.get('some url', {params:SOME_PARAMS}), SOME_PARAMS could be transformd to key-value params when it is a simple key-value data like {color:'red'}, and it would transform params to json string when it is a complex type like {cat:{color:'red'}}.
So to solve your question, I suggest that add params behind url like:
$http.get('some URL?cat[color]=red').success.....
Am very new to angularjs and i need to post data to a web service, the service accepts two parameters, one is List of object and the other is securityToken,
Here is my code,
$scope.saveCompany=function(){
// alert("Save Company!!!");
var Companies={
Code: 'testMartin',
Name: 'company1',
CompanyType : 'Tenant',
email : 'test#yaoo.com',
Fax : 4235353,
ParentID : 1
};
$http({
url:'http://localhost/masters/smstools.svc/json/SaveComapnies',
dataType: 'json',
method: 'POST',
data: $.param(Companies),
headers: {
"Content-Type": "text/json",
}
}).success(function(response){
alert ("Success");
}).error(function(error){
alert ("Save company!");
});
how can i pass the security token with the companies object as a separate paramenter. my service accepts the parameters like this,
public List<CompanyProfile> Save(List<CompanyProfile> CompanyList,string securityToken)
Since this is a rest call you only have 3 places were you can pass parameters data:
With Post and it will be part of the body, it seems this is what is your first parameter is occupying now.
With Get and you add the parameter to the URL /json/SaveComapnies/mySecParam or by queryString like /json/SaveComapnies?sec=mySecParam but this is not secure nor recommended for security settings.
With header from angular Post:
**headers: {
"Content-Type": "text/json",
"mySecVar": "mySecParamValue"
}**
Server side version:
public List<CompanyProfile> Save(List<CompanyProfile> CompanyList){
WebOperationContext current = WebOperationContext.Current;
WebHeaderCollection headers = current.IncomingRequest.Headers;
if (headers["mySecVar"] != null){
// do something
}
}
You can read more about it here:
How to read HTTP request headers in a WCF web service?
Can you share more information in your Backend?
If it is actually a REST Backend I would rather use an angular $resource
https://docs.angularjs.org/api/ngResource
If you want to pass json object and string as post Parameter you should stick to the $http docs
https://docs.angularjs.org/api/ng/service/$http
In the post example you can pass both params in:
$http.post('/yourEndpoint', {jsonObj:yourCompaniesObj, secKey:yourSecretToken})....(sucess etc)
Typing from my cell - if you need more code examples just tell
I am trying to send an JSON object to my webservice which is expecting JSON in the request data.
This my POST call from angularJS
$http({method: 'POST',
url: 'update.htm',
data: $.param($scope.cover),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
// handle
});
Value for cover object
$scope.cover = {id:1, bean:{id:2}}
Iam getting 500 (InvalidPropertyException: Invalid property 'bean[id]' of bean class [BookBean]: Property referenced in indexed property path 'bean[id]' is neither an array nor a List nor a Map;)
In network, it is sending in this way
bean[id]:1
I think it should send like
bean.id:1
How to reslove this issue. Thanks in advance
Looks like the data is getting to the server and is causing an error there. There's a possible duplicate question that's been answered here - Post Nested Object to Spring MVC controller using JSON
Try posting your data like:
$http({method: 'POST',
url: 'update.htm',
data: $scope.cover,
}).success(function (data) {
// handle
});