Vue-resource can't get response body when HTTP error 500 - rest

I'm trying to handle an HTTP 500 error using vue-resource (1.2.1) this way:
const resource = Vue.resource('items');
resource.get().then(
(response) => {
// Do something with response.body
},
(error) => {
// Do something with error.body,
// even if the HTTP status code is 500.
// But for now it's null...
}
);
There is nothing in error.body, while the actual server's response have something to say... And I really want to get this data to be displayed in a cool way for my app's users to be aware of what's going on (rather than opening dev tools and inspect network's response data).
Is there something I'm missing in Vue http config? Or maybe server-side, does my API needs to respond in a specific way? Or even respond special headers? Or, is it simply a limitation (or a bug) of vue-resource?
EDIT
Here is the content of error, picked from a console.log:
Response {
body: "",
bodyText: "",
headers: Headers…,
ok: false,
status: 0,
statusText: "",
url: "http://my.domain/items",
data: ""
}
And, the content of the actual server response (which I expected to be into error.body, but is not), picked from "network" tab in dev tools :
{
"success": false,
"error": {
"message":"this is the error message",
"details":[],
"stackTrace":[]
}
}

Related

How to create a chrome webRequest to validate response code

I want to check if my Linkedin Pixel tag is installed properly inside my webpages.
To validate, I would need to get a 302 response when the tag is fired.
Trying to create a chrome extension that could perform this validation.
chrome.webRequest.onSendHeaders.addListener(
(e) => {
console.log(e);
},
{
urls: ["https://px.ads.linkedin.com/*"],
}
);
--console.log object--
{documentId: 'E3A1D48B4697AC34E10A4D2A888CC8A9', documentLifecycle: 'active', frameId: 0, frameType: 'outermost_frame', initiator: 'https://www.theb2bhouse.com', …}
documentId: "E3A1D48B4697AC34E10A4D2A888CC8A9"
documentLifecycle: "active"
frameId: 0
frameType: "outermost_frame"
initiator: "https://www.theb2bhouse.com"
method: "GET"
parentFrameId: -1
requestId: "2395"
tabId: 2
timeStamp: 1652447005855.711
type: "image"
url: "https://px.ads.linkedin.com/collect?v=2&fmt=js&pid=2742940&time=1652447005855&url=https%3A%2F%2Fwww.theb2bhouse.com%2F"
[[Prototype]]: Object
Does anyone know how to send a webRequest to check if this above details got back a 302-redirect response?
On my inspect -> network request, I could see that the tag is fired correctly and recieved a response code of 302. Yet, I find the correct method to do the validation on webRequest.

How can I reach the 'Retry-After' response header using axios?

I'm building a simple Vue2 app with Auth section, which makes requests to REST API service.
So, I have my axios instance:
const instance = axios.create({
baseURL: BASE_URL,
timeout: DEFAULT_TIMEOUT,
withCredentials: true,
headers: {
accept: 'application/json',
},
});
To make authorization requests I use a separate module:
const auth = (api) => ({
submitPhoneNumber({ userPhone }) {
return api.get(`auth/${userPhone}`);
},
});
And set it all up together like this:
export default {
auth: auth(instance),
};
Then I add my api to Vue as a plugin:
export default {
install(Vue) {
const vueInstance = Vue;
vueInstance.prototype.$api = api;
},
};
In the component I access my api-plugin and make a request, extracting status and headers from it:
const { status, headers } = await this.$api.auth.submitPhoneNumber({
userPhone: this.userPhone,
});
When I look through the response in chrome devtools, I clearly see a "retry-after" header with number of seconds, after which I can make another request.
Upon receiving the response, I would like to save this number of seconds to some variable and then render a warning message like "Please wait { seconds } to make another submit".
The problem is that in my code I have no such header in the response (while I can see it in devtools, a I said):
see the screenshot
So, when logging the headers from my response, there are just these:
{content-length: '19', content-type: 'application/json; charset=utf-8'}
What is the problem with that?
Try var retrysec = error.response.data.retry_after that worked for me

How do I deal with "No 'Access-Control-Allow-Origin' header is present" on a physical phone?

I'm getting what seems to be a common error. "No 'Access-Control-Allow-Origin' header is present" when I try to retrieve the contents of a website on a physical phone (in this case an Android phone).
I've experienced something similar with ionic server where it was getting CORS errors, and resolved it by using proxies in the ionic.config.json file. But I understand I shouldn't have that issue on a physical device.
// searchString = "https://swapi.co/api/films";
searchString = "https://www.example.com";
console.log(searchString);
self.httpClient.get(searchString, { responseType: 'text' }).subscribe(
(data: string) => {
console.log("my data: " + data + " " + searchString);
},
(error: HttpErrorResponse) => {
console.log("my err: " + error.message);
console.log(error);
}
);
When I run it on the phone, if I use https://swapi.co the code returns the web page I expect.
If I use https://www.example.com, I get the following error in the phone's console.
XMLHttpRequest cannot load https://www.example.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. (index):1
my err: Http failure response for (unknown url): 0 Unknown Error 4.js:238
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false…}
error: XMLHttpRequestProgressEvent
headers: HttpHeaders
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
__proto__: __
The "right" solution seems to be to add a Access-Control-Allow-Origin header to https://www.example.com (which is probably what the owner of http://swapie.co did); however, I don't control that server so I can't.
How can I convince httpClient not to expect these headers?
You can't. CORS is there to prevent what you're trying to do, block cross origin requests for unapproved origins. Best you can try to do is lie about your host but you'll have to throw out your http client and write your own. but IOS or android may have seen you coming and taken measures to prevent such things.

Cache-control directive (only-if-cached) changed by dev-tools?

We are working on a Progessive Web App, for which the service worker intercepts the network traffic (via the fetch event handler). We have noticed, that sometimes a certain request fails here, because Request.cache is only-if-cached and Request.mode is no-cors, but not same-origin.
So it is similar to this problem.
Then I've noticed, that this happens only when the Chrome (v 65) DevTools are not opened. Does anybody notice the same phenomenon and does anybody have an idea, why this happens this way?
Parts of the request:
bodyUsed: false,
cache: "only-if-cached",
credentials: "include",
destination: "unknown",
headers: Headers {},
integrity: "",
method: "GET",
mode: "no-cors",
redirect: "follow",
referrer: "",
referrerPolicy: "no-referrer-when-downgrade",
url: "https://example.com/path/to/app-name/#!
We are handling this problem like this, but I'm afraid, that this is not appropriate.
serviceWorkerGlobal.addEventListener('fetch', function(event)
{
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
var oStrangeRequest = event.request.clone();
console.log('Fetch. Request cache has only-if-cached, but not same-origin.',
oStrangeRequest.cache, oStrangeRequest.mode,
'request redirect:',
oStrangeRequest.redirect, oStrangeRequest.url, oStrangeRequest);
return;
}
// ...
});
This is a bug. You can check the progress of the fix here: https://bugs.chromium.org/p/chromium/issues/detail?id=823392

How to handle Header "Access-Control-Allow-Origin" using ampersand-rest-collection?

Trying to request cors request with code:
export default Collection.extend({
model: person,
url () {
return 'http://127.0.0.1:5000/person/'
},
ajaxConfig: function () {
return {
headers: {
'Access-Control-Allow-Origin': 'http//:127.0.0.1:3000'
},
xhrFields: {
withCredentials: false
}
};
},
})
I'm sending request with http//:127.0.0.1:3000 but if use * i still get error below
XMLHttpRequest cannot load http://127.0.0.1:5000/person/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
How to handle this kind of request?
Rather than your Collection sending the 'Access-Control-Allow-Origin': 'http//:127.0.0.1:3000' in its request headers, your server at http://127.0.0.1:5000 needs to send it in its response headers to the pre-flight request.
If you can give some details about the server setup, I can help you to figure out how to add the header to the response.