How to send path parameters in javascript? - javascript

So I've been researching this for days and have not been able to find the answer online. I'm creating an API in AWS API Gateway and noticed the difference between 'path parameters' and 'query parameters'. I already read and know the differences, when each of them should be used, etc. However, what I can not find is HOW to implement and send the path parameters?
For example, when it comes to query parameters you can send those in the 'data' part of ajax jQuery. Easy. But again, how can I include the path parameters in that ajax call? I can set the path on API GATEWAY but not sure how to send the data for it from the front end. Any help would be greatly appreciated. Thanks.
Example: root/{Animal}/
How to send the "animal" i.e. 'dog' as a path parameter instead of a query parameter? i.e. /?animal=dog

You just need to form the URL string, and don't send any data with that.
let animal = 'dog';
$.ajax({
url: serviceUrl + '/' + animal,
method: 'GET',
success: function(res) { // your code }
});
If you are taking input from a textbox with id txtSearchAnimal:
let animal = $('#txtSearchAnimal').val();
And use the above ajax call.

Related

How to hide an api key in AJAX request

I would like to done an ajax request directly done by client on desktop.
Problem is my ajax request need a "secret api Key". I don't want the client has an access to this api key.
Here my currently js code:
var url = 'myurl';
var obj = new Object();
obj.api_key = "myKeyIwantToHide";
$.ajax({ url: url,
type: 'post',
dataType: 'json',
data: obj,
cache: false,
success: function(result){
alert(result);
}
});
It is possible to hide information to client with javascript in order to done my ajax request.
Thx,
Christophe
You cannot hide the api key completely from client. But if your client is non technical. You can make it hard for him/her to find api key. If you are using MVC you can set the api key when the first request is sent to the Index method and on return you can set it to a javascript variable. In this way user wont be able to see hardcoded value unlike in the code you have shown. If you are using ASP.NET then you can easily use ViewBag to set value to javascript variable using razor syntax.

How to make such a structure in javascript

I'm new to JS. And have a basic silly doubt. Please bear with me.I want to send a request of the form:
{"user":{"username":"myuser","password":"mypass","role":"myrole"}, "organization":"org_name"}
such that the user object can be access by req.body.user and organisation can be accessed by req.body.organization.
But when I'm sending this request:
it translates to-
{
"user[username]": "myuser",
"user[password]": "mypass",
"user[role]": "myrole",
"organization": "org_name"
}
When I just send
{"user":{"username":"myuser","password":"mypass","role":"myrole"}}
then I can access using req.body.user, but not the way mentioned above. Why is this so?
How can I send the request now such that I can access the request.body.user and req.body.organization properly?
EDIT:
This is how the request is sent. Front end: ember, backend node/express:
Ember.$.post("http://"+window.location.hostname+":3000/api/organizations/customer",{"user":{"username":"myuser","password":"mypass","role":"myrole"}, "organization":"org_name"},function(data){
console.log(JSON.stringify(data),null, " ");
});
Receiving side:
console.log(JSON.stringify(req.body,null," "));
I am trying to create the user but req.body.user is undefined. Though I can use user[username] and proceed, but that s now how I want to do
You aren't sending JSON to the server. Passing an object in as data doesn't send it as an object; it simply gets converted to a query string [source]. If you want to send JSON, you need to use JSON.stringify on the data that you send, not the data you receive.
Ember.$.post("http://"+window.location.hostname+":3000/api/organizations/customer",JSON.stringify({"user":{"username":"myuser","password":"mypass","role":"myrole"}, "organization":"org_name"}),function(data){
console.log(data);
});
With the help of Christian Varga's answer to this post, I could further dive in. Though the problem was still not solved, but it gave some insight of how can that be solved.
This is what I did next for such a structure. As per his suggestion, I used JSON.stringify but at a different place:
Ember.$.post("http://"+window.location.hostname+":3000/api/organizations/customer",{"user":JSON.stringify({"username":"myuser","password":"mypass","role":"myrole"}), "organization":"org_name"},function(data){
console.log(data);
});
On the backend server side I could then receive req.body.user. But the req.body.user was stringified JSON. To further access this inner JSON, I had to use JSON.parse.
Though this worked, but I was looking for more better solution, since this backend change worked for my front end implementation, but was failing for RESTClient.
I understood I need to pass the contentType of the data to be sent in the post request. I could not find $.post argument for contentType. So then I used $.ajax call.
Ember.$.ajax({
url: "http://"+window.location.hostname+":3000/api/organizations/customer",
type:"POST",
data: JSON.stringify({user:{username:username,password:password,role:role}, organization_id:organization_id}),
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function(data){
console.log(JSON.stringify(data),null, " ");
}
});
where the username, password, role, organization_id are already assigned variables.

BackBone - best way to send a server request

I'm new to Backbone and am just getting familiar with it.
I have a model and a collection - and view to the collection and a Form.
I'm sending request to get/get all/create by doing form.submit(), or something similar - which calls for the correct type [GET/POST/PUT] to the server using the base URL in the collection/model.
how do i send a non-trivial request? say that my base URL is /some/url , and i want to send /some/url/doSomething. should i directly send an ajax request with this URL or does backbone handle this in a more simpler way?
Thanks!
In backbone, you can pass url as an option to your model.fetch, model.save requests, etc to override the default declared in the model. You don't need to manually form an ajax request with $.ajax or anything like that.
If your URL does not pertain to a particular resource/model/collection, you may use raw jQuery ajax requests.
$.ajax({
method: 'GET',
url: '/some/url',
success: function(resp) { //handle response}
})
Best example of REST API is github api
example of merge a pull request (Merge Button):
PUT /repos/:owner/:repo/pulls/:number/merge
The main goal is using resources instead a commands. For example:
REST:
PUT /repos/:owner/:repo/pulls/:number/merge
{"commit_message":"mesg"}
NO-REST:
POST /merge
{"commit_message": "mesg", "owner": 123, "repo":"asd", "number": 1}
Cheers

Implementing Ajax calls for a REST API

I have built a back end REST API using Slim Framework and followed the REST format as close as I could.
Once I started working on the Front End I realized that AJAX works great with parameters and not paths
(param file?param=value , paths file/object/method/id)
I am planning on out sourcing or building an APP with xamarin or other 3rd party to consume the API, but for now a Alpha test will be done with HTML and AJAX calls.
Example call example.com/user/test or example.com/advertiser/2
So how do I query the API, do I just concat URL strings?
.ajax({ ... url : 'example.com/user/'+user ...});
EDIT:
Yes I know AJAX is domain sensitive, and Yes I am using verbs GET,POST,PUT and DELETE.
What is going on is the following :
When passing variables in an AJAX request they get appended as
PARAMS example.com/users/?user=Pogrindis
in an REST API at least as far as I read it goes
example.com/users/Pogrindis that's a path
reference parse.com/docs/rest#general-quick
Ajax has set definitions how to do this : https://api.jquery.com/jQuery.ajax/
Your passing user as a param, over get // post method and you are specifying what you expect back.
If i understood the question correctly you are looking at something like:
$.ajax({ url: 'example.com/user/',
data: {user: user}, // Params being sent
type: 'post',// Or get
dataType: 'json' // Or whatever you have
success: function(output) {
//.. do what you like
}
});
There should be no problem.
The data being passed into it will append to the url for GET-requests, i think thats what you mean.. Your data object can be constructed before sending via ajax.
There needs to be a route to query for data. Unless you define some flag on the server to point to the correct location, then you could pass through a route param but you need to have a pointer URL. Building the route can be painful, and subsequent calls will be more challenging but you can do it ?
After doing some research here is a solution used
FRONT END
$.ajax({
url: '/user/'+getid,
data: getdatastring,
type: 'GET',
datatype: 'json',
cache: false,
success: function(data) {
data = JSON.parse(data);
}
});
BACK END
SLIM PHP FRAMEWORK
$app->put('/user/:id', function($id) use ($app,$_pdo) {
$obj = new dbModel($_pdo);
$objApi = new Controller($obj);
$arrParams = json_decode($app->request()->getBody(),true);
$arrUser= $objApi->getUserInfo($id,$arrParams);
print json_encode($arrUser);
});

How to send data in request body with a GET when using jQuery $.ajax()

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

Categories

Resources