I'm occasionally seeing a failed XMLHttpRequest.send(). From Chrome's network panel I'm seeing a status of 0 - see below from the .har file. The code that runs the send() succeeds >99% of the time, but very occasionally (~ 1/300) it returns 0.
My question is: how do I catch this? Is there are callback that will catch it?
I'm currently using onload and onerror:
var xhr = new XMLHttpRequest();
xhr.onload = function(){};
xhr.onerror = function(){};
Neither of those are being called, so it's failing silently.
A few other things to note:
There is no evidence of the request in the server logs
There are no error messages in Chrome's console
The server is google app engine
Here's the .har file output. ##=redacted.
{
"startedDateTime": "2013-03-30T23:52:20.972Z",
"time": 97,
"request": {
"method": "GET",
"url": "https://www.#######.com/project/auth_upload?to_sign=PUT%0A%0A%0A%0Ax-amz-date%3ASat%2C%2030%20Mar%202013%2023%3A52%3A20%20GMT%0A/s3.#####.com/######.mp4%3FpartNumber%3D50%26uploadId%3D#################.w--&asset_id=#############&project_id=###########",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Referer",
"value": "https://www.######.com/console/###########"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.152 Safari/537.22"
}
],
"queryString": [
{
"name": "to_sign",
"value": "PUT%0A%0A%0A%0Ax-amz-date%3ASat%2C%2030%20Mar%202013%2023%3A52%3A20%20GMT%0A/s3.#######.com/############.mp4%3FpartNumber%3D50%26uploadId%3D##############"
},
{
"name": "asset_id",
"value": "###########"
},
{
"name": "project_id",
"value": "###############"
}
],
"cookies": [],
"headersSize": 595,
"bodySize": 0
},
"response": {
"status": 0,
"statusText": "",
"httpVersion": "HTTP/1.1",
"headers": [],
"cookies": [],
"content": {
"size": 0,
"compression": 0
},
"redirectURL": "",
"headersSize": 13,
"bodySize": 0
},
"cache": {},
"timings": {
"blocked": 0,
"dns": -1,
"connect": -1,
"send": -1,
"wait": -1,
"receive": null,
"ssl": -1
}
}
thanks,
tom
It seems that statusCode 0 indicates that response is empty even headers are not sent, that is something hard to figure out and you need to find it out yourself
but you said that the response doesn't arrive in your functions is because you are using load and error events for listening for the response, and actually you shouldn't entirely depend on those two errors, consider as case where timeout has occured before your request gets completed then 'timeout' event will be fired not 'error'
Instead you should use readystatechange event that will be called on every state change of request and you can also keep track of timeouts or errors related to no response received
httpRequest.onreadystatechange = stateChangeHandler;
stateChangeHandler = function() {
// The readyState can be 4 values:
// 0 - uninitialized
// 1 - loading
// 2 - loaded
// 3 - interactive
// 4 - complete
//
// readyState 0 - 3 can be completely ignored by us, as they are only updates
// about the current progress. Only on readyState 4, should we continue and
// start checking for the response status.
if (xmlHttpRequest.readyState != 4) {
return;
}
// Check HTTP Response code
if (xmlHttpRequest.status != 200) {
// response is ok process it
} else {
// there was some error
}
}
Reference:
https://developer.mozilla.org/en-US/docs/HTTP#HTTP_Response_Codes
http://www.w3.org/TR/XMLHttpRequest/#event-xhr-readystatechange
http://msdn.microsoft.com/en-us//library/ms534361%28en-us,VS.85%29.aspx
http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute
Related
From a request call to the marvel API I receive the following
{
"id": 1011334,
"name": "3-D Man",
"description": "",
"modified": "2014-04-29T14:18:17-0400",
"thumbnail": {
"path": "http://i.annihil.us/u/prod/marvel/i/mg/c/e0/535fecbbb9784",
"extension": "jpg"
},
How can I change the thumbnail.path to be https instead of HTTP because when I deploy the app I get the warning of mixed content saying it will be change automatically
You can change the value of response after response received. for example:
axios.get('/post?ID=12345')
.then((response) => {
const modifiedResponse = response.data;
modifiedResponse.thumbnail.path =
modifiedResponse.thumbnail.path.replace("http", "https");
// I see you tagged react
this.setState({post: modifiedResponse});
})
Please share more code if it seems my answer is ambiguous.
I will try to explain my problem as best as possible for me.
I'm using Strapi as a backend and Nextjs as a frontend.
For the authentication I using NextAuth.
[...nextauth].js:
const options = {
providers: [
Providers.Credentials({
name: 'Credentials',
credentials: {
username: { label: "Email", type: "email", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
authorize: async (credentials) => {
try {
const user = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/auth/local`, {
identifier: credentials.username,
password: credentials.password,
});
if (user.data) {
return user.data
} else {
return null
}
} catch (error) {
const errorMessage = error.response.data.message[0].messages[0].message
throw new Error(errorMessage)
}
}
}),
],
database: process.env.NEXT_PUBLIC_DATABASE_URL,
session: {
jwt: true,
},
callbacks: {
jwt: async (token, user) => {
if (user) {
token.jwt = user.jwt;
token.user = user.user;
}
return Promise.resolve(token);
},
session: async (session, token) => {
session.jwt = token.jwt;
session.user = token.user;
return Promise.resolve(session);
},
},
pages: {
signIn: '/login',
error: '/login'
},
};
const Auth = (req, res) =>
NextAuth(req, res, options);
export default Auth;
When I send form with identifier and password I getting session response with user data and jwt.
Everything working well, but if user objects have few more objects assigned to him, then something goes wrong and the session is empty.
Example:
I creating in Strapi simple collection with just two fields - image field, and owner (relation to user). Every response with image contents few lines:
"photo": {
"_id": "60ca03fa20bd43033a53950e",
"name": "Zrzut ekranu 2021-06-16 o 14.59.48.png",
"alternativeText": "",
"caption": "",
"hash": "Zrzut_ekranu_2021_06_16_o_14_59_48_2bc223567b",
"ext": ".png",
"mime": "image/png",
"size": 170.69,
"width": 668,
"height": 636,
"url": "/uploads/Zrzut_ekranu_2021_06_16_o_14_59_48_2bc223567b.png",
"formats": {
"thumbnail": {
"name": "thumbnail_Zrzut ekranu 2021-06-16 o 14.59.48.png",
"hash": "thumbnail_Zrzut_ekranu_2021_06_16_o_14_59_48_2bc223567b",
"ext": ".png",
"mime": "image/png",
"width": 164,
"height": 156,
"size": 14.92,
"path": null,
"url": "/uploads/thumbnail_Zrzut_ekranu_2021_06_16_o_14_59_48_2bc223567b.png"
},
"small": {
"name": "small_Zrzut ekranu 2021-06-16 o 14.59.48.png",
"hash": "small_Zrzut_ekranu_2021_06_16_o_14_59_48_2bc223567b",
"ext": ".png",
"mime": "image/png",
"width": 500,
"height": 476,
"size": 121.79,
"path": null,
"url": "/uploads/small_Zrzut_ekranu_2021_06_16_o_14_59_48_2bc223567b.png"
}
},
When I add 1 or 2 items with image and try to login to user who own that items then everything is fine, I can log in and receive full user object and jwt token.
But when I add 3 items there, session object is empty, and I can't log in. I do not receiving user object and jwt token.
With 3 items
With 2 items
When I using postman, even with 50 items response is good and include full user object and jwt token.
I think is because response is too large or something like that, but I have no clue how to deal with it.
I working on localhost (both - frontend and backend) on MacOS.
Is there anyone who can help me find a solution for that problem?
Kind Regards,
GP
The reason of above issue is that in api response is passed to many data, and next-auth store that all data in JWT, and JWT is stored in full in cookie, cookie is limited to 4096 bytes, and that simply brake that limit and response.
The simplest way to sort it out is to save only most important data in JWT.
You can do that in callback function.
I have a search result like whcih is given below :
{
"root": {
"id": "toplevel",
"relevance": 1,
"fields": {
"totalCount": 20
},
"coverage": {
"coverage": 100,
"documents": 20,
"full": true,
"nodes": 1,
"results": 1,
"resultsFull": 1
},
"children": [{
"id": "group:string:Jones",
"relevance": 9870,
"value": "Jones",
"fields": {
"sum(price)": 39816
}
},
{
"id": "group:string:Brown",
"relevance": 8000,
"value": "Brown",
"fields": {
"sum(price)": 20537
}
}
]
}
}
I do not want fields and coverage in my search results. How can I achieve this?. And also I want to change status according to error with error message. How can I do this? Please help.
Response payload: You can create your own renderer to control the returned format: https://docs.vespa.ai/documentation/result-rendering.html
HTTP status code: The rules for determining the status code to return are:
If the Result contains no errors (Result.hits().getError()==null): 200 OK is returned.
If the Result contains errors and no regular hits: If the error code of any ErrorMessage in the Result (Result.hits().getErrorHit().errorIterator()) is a "WEB SERVICE ERROR CODE", the first of those is returned. Otherwise, if it is a "HTTP COMPATIBLE ERROR CODE", the mapping of it is returned. Otherwise 500 INTERNAL_SERVER_ERROR is returned.
If the Result contains errors and also contains valid hits: The same as above, but 200 OK is returned by default instead of 500.
WEB SERVICE ERROR CODES:
200, 301, 302, 307, 400, 401, 403, 404, 405, 406, 408, 428, 429, 431, 500, 501, 502, 511
HTTP COMPATIBLE ERROR CODES:
com.yahoo.container.protect.Error.BAD_REQUEST -> Http code 400
com.yahoo.container.protect.Error.UNAUTHORIZED -> Http code 401
com.yahoo.container.protect.Error.FORBIDDEN -> Http code 403
com.yahoo.container.protect.Error.NOT_FOUND -> Http code 404
com.yahoo.container.protect.Error.INTERNAL_SERVER_ERROR -> Http code 500
com.yahoo.container.protect.Error.INSUFFICIENT_STORAGE -> Http code 507
With this information, you can write a Searcher component (https://docs.vespa.ai/documentation/searcher-development.html) which sets an ErrorMessage in the Result corresponding to the HTTP status you want.
For a real world example see e.g the rate limiting Searcher bundled in Vespa: https://github.com/vespa-engine/vespa/blob/master/container-search/src/main/java/com/yahoo/search/searchers/RateLimitingSearcher.java#L133
To customize results you can use a result renderer. Please take a look at https://docs.vespa.ai/documentation/result-rendering.html which should be complete with examples.
In my Alexa skill, I'm broadcasting an MP3 file through AudioPlayer Directive.
As the file starts playing, I get:
{
"type": "AudioPlayer.PlaybackStarted",
"requestId": "requestId",
"timestamp": "2018-02-28T13:17:54Z",
"locale": "en-US",
"token": "tokenstring",
"offsetInMilliseconds": 0
}
My service does not generate a response to this event, but I receive this error immediately:
{
"type": "System.ExceptionEncountered",
"requestId": "requestId,
"timestamp": "2018-02-28T13:17:55Z",
"locale": "en-US",
"error": {
"type": "INVALID_RESPONSE",
"message": "An exception occurred while dispatching the request to the skill."
},
"cause": {
"requestId": "amzn1.echo-api.request.8492b40e-1698-409f-8bed-61dc1f3de663"
}
}
In the documents it says I don't have to respond to this event, but is there something mandatory I need to send back to the Alexa? Maybe an HTTP status?
I found your question while looking for the same answer for myself.
I also found some notes in the Amazon Developer forums that there were some changes made some time back to require a response, but that documentation hadn't been fully updated...
I've added this below and its cleared up the issue for me.
if(event.request.type == 'AudioPlayer.PlaybackStarted' || event.request.type
== 'AudioPlayer.PlaybackStopped') {
response = {
"version": "1.0",
"response": {
"shouldEndSession": true
}
};
}
Hope that helps.
I've got an app based on djangoappengine, Backbone.js and Django REST Framework that uses PATCH requests to update models via {patch: true} on a model.save call.
I've found that when testing locally the dev_appserver returns:
ERROR 2014-02-19 04:37:04,531 dev_appserver.py:3081] code 501, message Unsupported method ('PATCH')
INFO 2014-02-19 04:37:04,532 dev_appserver.py:3090] "PATCH /api/posts/5707702298738688 HTTP/1.1" 501 -
Yet when I deploy it and access it through appspot the server happily accepts the request. Which forces me to deploy every time I make a change and want to test it.
I'm running the latests version (1.89) of the Python SDK, and found and old fixed issue that seems to tackle it but it seems other people have had it.
I tried this patch but it didn't make a difference. I don't understand why the development server would reject them and not the production server, is there something I need to change?
Thanks.
To update a resource, you can use POST with the x-http-method-override to patch. This is a valid RESTful operation and using POST will be more compatible with firewall and older user agents. The data in the request should indicate what is to be updated.
var url = '/api/posts/5707702298738688'
var patch_ops = [
{ "op": "replace", "path": "/properties/", "author": text}
{ "op": "add", "path": "/replies/", {"author": text, "comment":"blah"}}
/*
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
*/
];
var xhr = jQuery.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("X-HTTP-Method-Override", "PATCH");
},
url: url,
data: my_json_string,
dataType:"json",
success: function(data) {
return data;
},
error: function(xhr, textStatus, error){
return error;
}
});
Server handler:
def post(self, object_name):
if self.request.headers['x-http-method-override'] == 'PATCH':
# update according to patch operations
patch_ops_str= self.request.body.decode('utf-8')
try:
patch_ops = json.loads(new_area_geojson_str)
except:
self.response.set_status(400)
return self.response.out.write('{"status": "error", "reason": "JSON Parse error" }')
else:
self.response.set_status(405)
return self.response.out.write('{"status": "error", "reason": "post not accepted without x-http-method-override to PATCH" }')
Adapted from Please do not patch like an idiot