Axios Percent Encode on GET request - javascript

I'm trying to make a GET request in Axios with what I believe are "percent encoded" parameters. D
I am trying to call a URL that should resolve to:
https://example.com/api/list?pageSize=15&statusFilters=%5B"DELETED"%2C"DRAFT"%5D
Below is my code, however this resolves to https://example.com/api/list?pageSize=15&statusFilters[]=LIVE&statusFilters[]=DRAFT which for some bonkers reason returns a completely different set of results (not my API)
var params = {
pageSize: 15,
statusFilters: ["LIVE","DRAFT"]
}
return axios({
method: 'GET',
params,
url: `${API_URL}${url}`,
})

Related

Axios request to Opensearch/Elasticsearch

Currently able to GET and POST to my collection but need the ability for more complicated queries, I am using bodybuilder to structure the request and axios as my client.
However using POST doesn't return my specified results instead just the first 10 items in my index and using GET I'm unable to send a body for these complicated requests leaving me with POST.
I've switched setting my data from data:data to body:data with the same result.
Currently this is my POST which again returns data but NOT my filtered data just the first 10 items of my collection.
Any insight would be appreciated!
export function searchQuery(search: string) {
var body = bodybuilder().query("query_string", "query", search).build();
const data = JSON.stringify(body);
axios({
url: `${SEARCH_URL}`,
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: data,
}).then((res) => {
console.log(res);
});
}
This is my current log of data:
{"query":{"query_string":{"query":"Green"}}}
Based on the comments in the question above, you are getting only the first 10 items in your collection, when you run the query against elasticsearch directly.
This is because elasticsearch by default returns only 10 documents in the search result if no size param is included in the search query.
If you want to get more than 10 results, you need to modify your search query as
{
"size": 20, // change this according to your requirement
"query": {
"query_string": {
"query": "Green"
}
}
}

jQuery $.AJAX to replace with JavaScript fetch - mvc4 method arguments are always null

We had a working jQuery script which calls an MVC4 C# controller method like this:
// C# controller method
public ActionResult MyMethod(String text, String number)
{
... do something ...
... returns a partial view html result ...
}
// javascript call
var myData = { text:"something", number: "12" };
$.ajax({ url:ourUrl, type:"GET", data: myData,
success: function(data) { processAjaxHtml( data )}});
Now we want to replace this $.ajax call to a native fetch(...) call like this (and use a Promise):
function startAjaxHtmlCall(url) {
var result = fetch( url, {method: "GET", body: myData});
return result.then( function(resp) { return resp.text(); });
}
starAjaxCall(ourUrl).then( resp => processAjaxHtml(resp) );
We have problems, and somehow we cannot find the answers:
using GET we cannot attach body parameters (I see that the html GET and POST calls are quite different, but the $.ajax somehow resolved this problem)
we changed the GET to POST but the controller method still got "null"-s in the parameters
we changed the fetch call to "body: JSON.stringify(myData)" but the method still gots null
we constructed a temp class with the 2 properties, changed the method parameters as well - but the properties still contains null
we added to the [FromBody] attribute before the method class parameter but it got still nulls
we replace body: JSON.stringify(myData) to body: myData - still the same
Note: we tried this in Firefox and Chrome, the code is MVC5, C#, .NET Framework 4.5 (not .CORE!) hosted by IIS.
We changed the javascript call as the following (and everything works again):
var promise = new Promise((resolve, reject) => {
$.ajax({
url: url,
method: method,
data: myData,
success: function(data) { resolve(data); },
error: function(error) { reject(error); },
});
});
return promise;
// note: .then( function(resp) { return resp.text(); }) // needs no more
So: what do we wrong? what is the information we do not know, do not understand about fetch? How to replace $.ajax to fetch in this situation correctly? can it works with GET again? how to modify the controller method to receive the arguments?
GET requests do not have a BODY, they have querystring parameters. Using URLSearchParams makes it easy
var myData = { text:"something", number: "12" };
return fetch('https://example.com?' + new URLSearchParams(myData))
.then( function(resp) { return resp.text(); })
Other way of building the URL
const url = new URL('https://example.com');
url.search = new URLSearchParams(myData).toString();
return fetch(url)...
If you were planning on sending JSON to the server with a post request
fetch('https://example.com', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(myData)
});

Getting an AJAX GET request to work with Express.js

I am using node.js and Express.js on the back end, and am trying to make a server call from the client via AJAX.
So I have this POST request that works fine with AJAX:
node.js/Express.js:
app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});
Client Side/AJAX request:
var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
The userInputForm comes from an HTML form.
This POST request works fine. But I want to change this to a GET request. If I change app.post to app.get, and change type in the AJAX call to GET, I get this 500 error:
GET /createNewThing?userInput= 500
When you make a GET request, the data appears in the query string (of the URL in the request headers). It doesn't appear in the request body. There is no request body.
When you try to read from the request body, you are trying to access a property of an undefined object, which triggers an exception and cause an internal server error.
This answer explains how to read a query string:
var id = req.query.id; // $_GET["id"]
So
var userInput = req.query.userInput;
I think var userInputForm = $('#userInputForm.val()') will get error or get wrong data..This may be the reason for the error. Due to userInputForm may not be a string and concatenate with userInput=
Actually it is bad data.
And for the data in ajax, you should modify data from data: "userInput=" + userInputForm,
to:
data: {
userInput: userInputForm
},
dataType: "json"
And var userInputForm = $('#userInputForm.val()')
to var userInputForm = $('#userInputForm').val();
At last, you could modify as bellow, I believe it works:
var userInputForm = $('#userInputForm').val();
$.ajax({
url: "/createNewThing?userInput=" + userInputForm,
type: "GET",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});

Can Mockjax handle single IDs Api from Json file

I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?
current code :
$.mockjax({
url: "/Api/Cases/{caseId}",
proxy: "/mocks/cases nuevo.json",
dataType: 'json',
responseTime: [500, 800]
});
$.ajax({
type: 'GET',
url: '/Api/Cases/',
data: {caseId: taskId},
success: function(data){
//use the returned
console.log(data);
}
});
current error:
GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)
Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.
Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:
$.mockjax({
url: /\/Api\/Cases\/(\d+)/, // notice the regex here to allow for any ID
urlParams: ['caseID'], // This defines the first matching group as "caseID"
responseTime: [500, 800],
response: function(settings, mockDone) {
// hold onto the mock response object
var respObj = this;
// get the mock data file
$.ajax({
url: 'mocks/test-data.json',
success: function(data) {
respObj.status = 200;
// We can now use "caseID" off of the mock settings.urlParams object
respObj.responseText = data[settings.urlParams.caseID];
mockDone();
},
error: function() {
respObj.status = 500;
respObj.responseText = 'Error retrieving mock data';
mockDone();
}
});
}
});
There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId, // this will add the ID to the URL
// data: {caseId: taskId}, // this adds the data to the query string
success: function(data){
//use the returned
console.log(data);
}
});
Note that this presumes the mock data is something like:
{
"13": { "name": "Jordan", "level": 21, "id": 13 },
"27": { "name": "Random Guy", "level": 20, "id": 27 }
}
What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId,
success: function(data){
//note you have to parse the data as it is received as string
data = JSON.parse(data);
var result = $.grep(data, function(e){ return e.caseId == taskId; });
//since i'm expecting only one result, i pull out the result on the 0 index position
requestedData = result[0];
}
});
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API, And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];
**Note: **
A more suited solution would be a mixture between what i've done and #jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:
[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]

Angular stripping dollar variable in http request

I have to send data with an HTTP GET request in angular js. Below is my data:
var model={
"$or":[
{name:'t1'},
{createdBy:
{
'$ne':'t2'
}}
]
}
My http request object is like below:
var url="abc.com/xyz";
var request = {
method: 'GET',
url: url',
params: model
};
I am getting createdBy object as {} object when I inspect the request , angular is stripping that variable which has $ in it. Please help me to solve this issue.

Categories

Resources