Servlet response format for dojo xhrPost error handler - dojo

To trigger the error handler for dojo's xhrPost, is there a specific format in which the server response is to be sent? Or just setting the status code to the required error code in the HttpServletResponse object does the work.
Thanks,
RR

You only need to set the appropiate HTTP status code in the HttpServletResponse. I think anything greater than or equal to 400 will be considered an error by the XHR object.
Of course you can also send actual content in your response (via its output stream) and set its content type. You'll receive that in your handler as well:
dojo.xhrPost({
url: '/request',
load: function(data, ioargs) { /* ... */ },
error: function(error, ioargs) {
// error is a Javascript Error() object, but also contains
// some other data filled in by Dojo
var content = error.responseText; // response as text
var status = error.status; // status code
}
});
You can also get responseText and status from ioargs.xhr, which is the full XmlHttpRequest object.

Related

Express res.send or res.json doesn't contain a body

I'm calling an API to fetch orders for a given user based on ID which are fetched from a third-party site. These are fetched correctly as a console.log them in the node server. But when I try to send the results back to the client neither res.send nor res.json results sending the data back to the client. Here is an example of an order from console.log:
{"customer":{"orders":{"edges":[{"node":{"id":"gid://shopify/Order/1234564564","lineItems":{"edges":[{"node":{"title":"Some title here"}}]}}}]}}}
Then on the client in the devtools when I console.log the response I get:
body:ReadableStream
locked:false
[[Prototype]]:ReadableStream
bodyUsed:false
headers:
Headers {}
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:9000/api/getOrders?cid=gid://shopify/Customer/1234564564"
[[Prototype]]:Response
Any help is appreciated.
=== UPDATE ===
I've now even tried the most basic of examples and am getting the same response on the client:
app.get('/testExpress', (req, res) => {
res.send("Hello")
});
Thanks to #laurent here is how I was able to receive that response on the client:
fetch('/testExpress')
.then(async (r) => {
const resp = await r.text();
console.log(resp);
})
You should try to get the json out of the response by const json = await response.json().
These are the available methods to parse the response body depending on what you want:
Response.arrayBuffer()
Returns a promise that resolves with an ArrayBuffer representation of the response body.
Response.blob()
Returns a promise that resolves with a Blob representation of the response body.
Response.clone()
Creates a clone of a Response object.
Response.formData()
Returns a promise that resolves with a FormData representation of the response body.
Response.json()
Returns a promise that resolves with the result of parsing the response body text as JSON.
Response.text()
Returns a promise that resolves with a text representation of the response body.
https://developer.mozilla.org/en-US/docs/Web/API/Response
The Response object is a representation of the http response. You should try to receive the body of the response by using one of these methods or parsing the body from the readable stream response.body.

How to read the contents of a Post request on Postman?

In the systems I am testing, there are cases that the response informs 200 (ok), but the content may indicate an error in the internal validations of the backend service. How can I read the contents of the response with Postman and schedule a successful validation if this service error code comes as expected?
You can use the tests tab in Postman to run checks on the body (JSON and XML). There are snippets which show you the syntax. You can adapt them to check for the element of the response body which indicates the error.
Postman has a tab called "Tests" where you can provide you test script for execution.
If you want to validate your request responded with 200 OK, following is the script
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
If you want to validate the response contains any specified string,
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
In your case am assuming the above script can be used. In case the response body is JSON,
pm.test("JSON Body match", function () {
var respBody = pm.response.json();
pm.expect(respBody.<json node>).is.to.equal("Error_name");
});
Example JSON response body
{
"id" : 100,
"status" : "Bad Request"
}
pm.test("JSON Body matches string", function () {
var respBody = pm.response.json();
pm.expect(respBody.status).is.to.equal("Bad Request");
});

Sending a file with XMLHttpRequest() to Tika server

I'm trying to send a PDF for content extraction to a Tika Server but always get the error: "Cannot convert text from stream using the source encoding"
This is how Tika is expecting the files:
"All services that take files use HTTP "PUT" requests. When "PUT" is used, the original file must be sent in request body without any additional encoding (do not use multipart/form-data or other containers)." Source https://wiki.apache.org/tika/TikaJAXRS#Services
What is the correct way of sendig the file with XMLHttpRequest()?
Code:
var response, error, file, blob, xhr;
file = new File("/PROJECT/web/dateien/ai/pdf.pdf");
blob = file.toBuffer().toBlob("application/pdf");
url = "http://localhost:9998/tika";
// send data
try {
xhr = new XMLHttpRequest();
xhr.open("PUT", url);
xhr.setRequestHeader("Accept", "text/plain");
xhr.send(blob);
} catch (e) {
error = e;
}
({
response: xhr.responseText,
status: xhr.statusText,
error: error,
type: xhr.responseType,
blob: blob
});
Error:
I suspect PUT request to be converted into a POST request by wakanda when there is blob in XHR body. Can you wireshark your XHR request and add details ? If so, you can probably fill an issue in wakanda (https://github.com/Wakanda/wakanda-issues/issues)
Hope it helps,
Yann

OSX - AFNetworking sending text even with JSON Serializer set

I have an issue with AFNetworking and AFJSONRequestSerializer. I try to access an API, and the request contains a text/plain header. Here's my code :
class BaseService {
var manager: AFHTTPRequestOperationManager!
init() {
manager = AFHTTPRequestOperationManager()
manager.responseSerializer = AFJSONResponseSerializer()
manager.requestSerializer = AFJSONRequestSerializer(writingOptions: NSJSONWritingOptions.allZeros)
}
}
class UserService: BaseService {
func startNewEntry(name: String) {
let params = [
"time_entry": [
"description": name,
"created_with": "fooBar"
]
]
manager.POST(
"endpoint",
parameters: params,
success: { (operation, response) -> Void in
let json = JSON(response)
println("OK")
println(json)
Context.shared.entries.getFromJSON(json)
}) { (operation, error) -> Void in
println("-- ERROR --")
println(operation)
println(error)
}
}
Do you know this issue ?
No, this code will create a request with a content type of application/json. But I wonder if you perhaps mislead by an error message that said:
Request failed: unacceptable content-type: text/html
If you got that, that's not telling you that that the request had an unacceptable content type, but rather that the request failed because the response was text/html. And this is a very common issue: If server code that is attempting to create a JSON response fails for some reason, sometimes the error message isn't JSON, but rather it's HTML.
I would suggest adding the following inside the failure block of your POST method in order to see what this text/html response was:
if operation.responseData != nil {
println(NSString(data: operation.responseData, encoding: NSUTF8StringEncoding))
}
This way, if you get a text error message from the server (e.g. the request was malformed or what have you), you'll be able to read the HTML response you got back.

dojo jax-rs call issue

I'm trying to call a REST webservice using dojo toolkit it seems that the call is encountring some isues this is the call with dojo
dojo.xhrGet({
url: 'http://localhost:9080/TestJMSWeb/jaxrs/categories/all',
handleAs: 'json',
timeout: 2000,
load: callback
});
var callback = dojo.hitch(this, function(data) {
var massagedData = {
label: 'categorie',
identifier: 'id',
items: data
}
this.store = new dojo.data.ItemFileReadStore({data: massagedData});
});
the webservice code is here
#GET
#Path("/all")
#Produces("application/json")
public JSONArray getAllCategories() throws IOException {
final List<Categorie> allCategories = manager.getCategories();
if (allCategories == null || allCategories.isEmpty())
throw new WebApplicationException(ErrorUtil.jSONArrayResponse(Status.NO_CONTENT, "No category found"));
JSONArray jsonArray = jsonCustomerArray(allCategories);
return jsonArray;
}
when I call the webservice I get an error message
ResourceRegis I org.apache.wink.server.internal.registry.ResourceRegistry filterDispatchMethods The system cannot find any method in the ressources.CategorieRessouce class that supports OPTIONS. Verify that a method exists.
[4/24/12 1:23:41:531 GMT] 0000002f SystemErr R 0 TestJMSWeb INFO [WebContainer : 0] openjpa.Runtime - OpenJPA dynamically loaded a validation provider.
it seems that is trying to call the ressource with the OPTIONS method while I'm using the .xhrGet function what is the problem?
Here is a link describing the problem: http://engin.bzzzt.biz/2010/01/22/first-dojo-impression/
The guy talks about how if it is a cross domain request (which I believe yours is, because of the ports), and the request contains some Access-Control-* HTTP headers, than browsers will send the request as OPTIONS instead of GET.
Dojo adds the Access-Control-* headers when it determines you are making a cross domain request. You can try to fix this yourself by going to dojo/_base/xhr.js and commenting out the following lines (723 to 729):
// FIXME: is this appropriate for all content types?
if(args.contentType !== false){
xhr.setRequestHeader("Content-Type", args.contentType || _defaultContentType);
}
if(!args.headers || !("X-Requested-With" in args.headers)){
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
I haven't tried this fix yet so please let me know if it works!