temporarily change $http.defaults.transformResponse - ajax

How can I customize $http in angularjs such that it will accept strings as its response in a $http.post call? Right now, when I do a $http.post call, my response is in string but angularjs by default uses JSON therefore I get an error. Right now I have something along the lines of
function getResponseURL(response) {
//this will convert the response to string
return response;
}
$http.defaults.transformResponse = [];
$http.defaults.transformResponse.unshift(getResponseURL);
However if I use the code above, any $http.post calls after that call uses string. I want it to use the original default JSON format. How can I go about into just temporarily changing the response to string for this one call but the rest stay as JSON type as a response?

Why not only register that transform for ONLY that request?
Angular js $http docs
If you wish
override the request/response transformations only for a single
request then provide transformRequest and/or transformResponse
properties on the configuration object passed into $http.

Related

How to access request body in cy.route response callback?

I have built something that can capture network requests and save them to a file. Currently I am now trying to build the second part which should return these captured requests, but running into some difficulties. Sometimes I have multiple requests going to a single method/url combination, and I need to return a different response depending on the request body. The problem I am facing is illustrated in the example below:
cy.route({
url: 'api.example.com/**',
method: myMethod,
response: routeData => {
// I can set the response here
// But I don't have access to the request body
},
onRequest: xhr => {
// I can access the request body here
// But I am not supposed/able to set the response
},
})
If I understand the API docs correctly, I am supposed to set the response in the response callback. However, in that callback I do not seem to have access to the XHR object from which I could read the request body.
Is there a way to access the request body in the response callback?
Or, alternatively, is there a way to set the response from the onRequest callback?
Update: just saw this post which mentions a body property which can be added to the cy.route options object. I don't see this in the cypress route docs so I don't know if this is even a valid option, and I also wouldn't know if making multiple calls to cy.route with an identical method and url, but a different body would produce the correct results. If this was of any use, I would have hoped to have seen some branching logic based on a body property somewhere in this file, so I am not super hopeful.
Cypress v6 comes with the cy.intercept API. Using that is much more convenient than using cy.server and cy.route.

Send object with axios get request [duplicate]

This question already has answers here:
Axios get in url works but with second parameter as object it doesn't
(4 answers)
Closed 5 years ago.
I want to send a get request with an object. The object data will be used on the server to update session data. But the object doesn't seem to be sent correctly, because if I try to send it back to print it out, I just get:
" N; "
I can do it with jQuery like this and it works:
$.get('/mysite/public/api/updatecart', { 'product': this.product }, data => {
console.log(data);
});
The object is sent back from server with laravel like this:
public function updateCart(Request $request){
return serialize($request->product);
The same thing doesn't work with axios:
axios.get('/api/updatecart', { 'product': this.product })
.then(response => {
console.log(response.data);
});
I set a default baseURL with axios so the url is different. It reaches the api endpoint correctly and the function returns what was sent in, which was apparently not the object. I only get "N; " as result.
Axios API is a bit different from the jQuery AJAX one. If you have to pass some params along with GET request, you need to use params property of config object (the second param of .get() method):
axios.get('/api/updatecart', {
params: {
product: this.product
}
}).then(...)
You can pass either a plain object or a URLSearchParams object as params value.
Note that here we're talking about params appended to URL (query params), which is explicitly mentioned in the documentation.
If you want to send something within request body with GET requests, params won't work - and neither will data, as it's only taken into account for PUT, POST, DELETE, and PATCH requests. There're several lengthy discussions about this feature, and here's the telling quote:
Unfortunately, this doesn't seem to be an axios problem. The problem
seems to lie on the http client implementation in the browser
javascript engine.
According to the documentation and the spec XMLHttpRequest ignores the
body of the request in case the method is GET. If you perform a
request in Chrome/Electron with XMLHttpRequest and you try to put a
json body in the send method this just gets ignored.
Using fetch which is the modern replacement for XMLHtppRequest also
seems to fail in Chrome/Electron.
Until it's fixed, the only option one has within a browser is to use POST/PUT requests when data just doesn't fit into that query string. Apparently, that option is only available if corresponding API can be modified.
However, the most prominent case of GET-with-body - ElasticSearch _search API - actually does support both GET and POST; the latter seems to be far less known fact than it should be. Here's the related SO discussion.

Set default WebAPI formatter

We are using WebAPI to mimic the handling of a legacy system. As a result, we would like the default response formatter to be the XmlFormatter and not the JsonFormatter. The reason is that some of the existing calls to the service do not supply the Accept: HTTP header field.
I can achieve this by removing the JsonFormatter from the Formatters collection and then re-adding it, forcing it to be at the end of the chain.
This then result in the default format response using the XmlFormatter. Although it works, it just doesn't feel correct, and although I am moving Json to the back of the collection, there is no guarantee that the XmlFormatter is at the front of the collection.
Ideas/thoughts?
Just add formatters in the right order. If ASP.NET Web API finds two formatters for the same content type, it will pick the first one, so it is very important to add formatters in the right order.
//somewhere in Web Api config
config.Formatters.Clear();
config.Formatters.Add(new XmlMediaTypeFormatter());
config.Formatters.Add(new JsonMediaTypeFormatter());
So the default will be XML, the first formatter, but the API still supports JSON if the request asks for it (with appropriate HTTP header).
Finally, another different approach, is to use a custom IContentNegotiator. It will allow you to select the most appropriate MediaTypeFormatter for a given request.
//somewhere in Web Api config
config.Services.Replace(typeof(IContentNegotiator), new MyCustomContentNegotiator());
An example is available here.
This is returned to automatically serialise and return json when content type is json.
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;

How to send Object via Ajax to Servlet

How do I send an element of type object via ajax to a servlet?
In the ajax I am passing the value as follows below:
data: { mapList : mapLists }
To get the value in the Servlet am doing follows below:
Object o = request.getAttribute("mapList");
System.out.println(o);
However, the returned value is always null. What should I do to get around this problem?
Change your ajax datas by :
data: { 'mapList' : mapLists }
On HTTP GET or POST requests you can only send a list of key/value pairs as parameters to the server so you will have to manually serialize your object to send its attributes in this format.
You should better use HttpServletRequest.getParameter(String) in place of HttpServletRequest.getAttribute(String). Also, what you get as an HTTP GET/POST parameter will always be received in the servlet as a String.
I assume that you are using jQuery to send the ajax request. I also asume that your mapLists variable is a json object. As far as I know, jQuery doesn't automatically convert a json object to a key/value pair HTTP parameter list so you will have to do it by yourself and then parse it back in the servlet. You can use JSON.stringify() to convert your json object or you can serialize it manually.

ajax response for node file

so still a newb to nodeJS and back end code in general. I need some help with ajax and node. For instance I have a function that goes like this
function random(response) {
var objToJson = {...};
response.write(objToJson);
response.end();
}
if instead of writing I want to pass this json object to another function as a response of an ajax call made to it how would that be?
Thanks for you help!
Node.js allows you to easy manipulate HTTP request and response objects.
Ajax still sends a HTTP request object and the Ajax onsuccess callback manipulates a HTTP response object.
Writing an object to a response for an ajax request allows your ajax success handler to manipulate that data.
There are abstraction libraries for RPC like now
It sounds like you want to return a javascript object to work with in your client-side code. While that's not possible directly (you can't send an object directly over HTTP; you're always serializing/deserialing in some fashion), you can certainly return a JSON payload and easily convert that to an in-memory javascript object. If that's what you're doing, you should set the response content type to application/json.
response.setHeader("Content-Type", "application/json");
If you're writing "pure" javascript (no framework wrapping XmlHttpRequest), you'll need to eval() the responseText to convert it to an object. If you're using something like jQuery, it will do that work for you (assuming you set the content type as suggested above).

Resources