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

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

Related

Can't login by Goggle accounts connect or by Google auth API in Cypress 10x

Current behavior
I've tried to connect to Google account when my tested application redirects to Google accounts connect for let the end-user send emails by the application but I'm not able to do it not by Google Auth API according to your guidelines:
https://docs.cypress.io/guides/end-to-end-testing/google-authentication#Custom-Command-for-Google-Authentication
and not by cy.origin() from the UI.
In the first attempt by the API it's ignore of these authentication and popup the dialog to connect by google account as usually even all the credentials and token are valid and return 200 ok.
In the second attempt by cy.origin() it's keep to load the page after the redirect and always reach to timeout and yell about to increase the timeout even the page seems like it was fully loaded after a few seconds.
I've tried to increase the timeout to 90 seconds and use wait() before and after the redirect and look for some hidden iframes and tried every versa of google domain but nothing help.
it always return errors over there.
all the examples are below.
This is the error when trying to use cy.origin()::
Timed out after waiting 30000ms for your remote page to load on origin(s):
- https://google.com
A cross-origin request for https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fmail.google.com&include_granted_scopes=true&state=%7B%22redirectUri%22%3A%22https%3A%2F%2Fmyappurl.com%2Fapp%2Fpipeline%2F9some-token-here-b96b599154ac%3Ftab%3Doverview%22%2C%22clientToken%22%3A%mytokenishere-1234567890%22%7D&prompt=consent&response_type=code&client_id=1234567890-aehhht36f7a01d38bmsvvpjrh915i86v.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fmyredreictedappurl.com%2FusersManagerSrvGoogleLogin was detected.
A command that triggers cross-origin navigation must be immediately followed by a cy.origin() command:
cy.origin('https://google.com', () => {
<commands targeting https://accounts.google.com go here>
})
If the cross-origin request was an intermediary state, you can try increasing the pageLoadTimeout value in Users/myname/repos/myreponame/cypress.config.ts to wait longer.
Browsers will not fire the load event until all stylesheets and scripts are done downloading.
When this load event occurs, Cypress will continue running commands.[Learn more](https://on.cypress.io/origin)
Desired behavior
No response
Test code to reproduce
commands.ts
Cypress.Commands.add('loginByGoogleApi', () => {
cy.log('Logging in to Google')
cy.request({
method: 'POST',
url: 'https://www.googleapis.com/oauth2/v4/token',
body: {
grant_type: 'refresh_token',
client_id: Cypress.env('googleClientId'),
client_secret: Cypress.env('googleClientSecret'),
refresh_token: Cypress.env('googleRefreshToken'),
},
}).then(({ body }) => {
const { access_token, id_token } = body
cy.request({
method: 'GET',
url: 'https://www.googleapis.com/oauth2/v3/userinfo',
headers: { Authorization: `Bearer ${access_token}` },
}).then(({ body }) => {
cy.log(body)
const userItem = {
token: id_token,
user: {
googleId: body.sub,
email: body.email,
givenName: body.given_name,
familyName: body.family_name,
imageUrl: body.picture,
},
}
window.localStorage.setItem('googleCypress', JSON.stringify(userItem))
cy.visit('/')
})
})
})
test-file.cy.ts
it.only('Send email to a user - is shown in the activity', () => {
cy.loginByGoogleApi();
cy.get(loc.sideNavBar.buyersPipeline).should('be.visible').click();
cy.get(loc.pipelineBuyer.nameColumn)
.eq(4)
.should('be.visible')
.click({ force: true });
cy.get(loc.buyerDetails.basicCard).should('be.visible');
cy.get(loc.buyerDetails.timelineSendEmailIcon)
.should('be.visible')
.click();
cy.get('div[role="dialog"]').find('button.MuiButton-root').should('be.visible').click();
})
})
By cy.origin() by the UI:
test-file.cy.ts
it.only('Send email to a user - is shown in the activity', () => {
// cy.loginByGoogleApi();
cy.get(loc.sideNavBar.buyersPipeline).should('be.visible').click();
cy.get(loc.pipelineBuyer.nameColumn)
.eq(4)
.should('be.visible')
.click({ force: true });
cy.get(loc.buyerDetails.basicCard).should('be.visible');
cy.get(loc.buyerDetails.timelineSendEmailIcon)
.should('be.visible')
.click();
cy.get('div[role="dialog"]').find('button.MuiButton-root').should('be.visible').click();
cy.wait(5000);
cy.origin('https://accounts.google.com', () => {
cy.wait(5000);
expect(window.origin).contains('google.com')
cy.get('input[type="email"]', {timeout: 60000}).should('be.visible', {timeout: 60000}).type('111');
})
});
````
### Cypress Version
10.7.0
### Node version
v14.19.1
### Operating System
macOS Montery 12.3.1

API requests(Mantis BT) from another domain - preflight error

I'm developing a Mantis BT client in ColdFusion but I have a problem when I try to make requests from a different domain.
If I making requests from the same domain where I installed Mantis BT all work fine but when I try to make a request from a different domain or the same domain with another port(localhost:8500 - ColdFusion) the browser return "Failed to load https://localhost/mantis/api/rest/users/me: Response for preflight has invalid HTTP status code 401." error.
I have added all headers in mantis config but it still not working.
If I try to make a request with postman all work fine.
var settings = {
"async": true,
"crossDomain": true,
"url": "localhost:8080/mantis/api/rest/users/me",
"method": "GET",
"headers": {
'Access-Control-Expose-Headers': 'Access-Control-Allow-Origin',
'Access-Control-Allow-Origin': '*',
'Authorization': 'MAzzT5UD4cjxwwOayyLFAXnlIPQJmiL_'
}
}
$.ajax(settings).done(function (response) { console.log(response); });
I resolved it by enable headers module in apache.

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

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":[]
}
}

Sails.js CORS for post method

I was able to use CORS for a specific controller using a GET request like the following:
'get /url': {
controller: 'somecontroller',
action: 'someaction',
cors: true
},
However if I try using POST like the following, I get "Access Denied" error:
'post /url': {
controller: 'somecontroller',
action: 'someaction',
cors: true
},
How do I setup cors for a post method?
in config/routes.js before declaring routes put :
'OPTIONS /*': function(req, res) {
res.send(200);
},
and in config/cors.js try to put :
module.exports.cors = {
allRoutes: true,
origin: '*',
credentials: true,
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
headers: 'content-type, access-control-allow-origin, authorization'
};
With my limited research I found out that simply adding "cors: true" to the controller doesn't solve the problem. Sails is still expecting a csrf token for the post method. In the bootstrap.js file under config folder, I added the following code at the bottom to disable csrf token on the route by using the following:
sails.config.csrf.routesDisabled = '/url';
If you have better solutions, please post them here. Thanks!
Edit: You can also change this in the config/csrf.js file. Change module.exports.csrf = true; to:
module.exports.csrf = {
routesDisabled: '/url',
};
You might have to use it for your apis
module.exports.csrf = {
routesDisabled: '/api/*',
};

Atmosphere request.onOpen never gets called. Client-Server connection stopped showing: "101 switching protocols"

I have downloaded the "atmosphere-chat" (jersey) and modified a little because I wanted it to be running inside Jetty.
Everithing is working on this side (in stand alone way). Atmosphere 2.2.0-RC3 / Jetty jetty-9.2.0.M1
But when I put those inside Mule the request.onOpen is never called.
Here is the piece of javascript code (I didn't change from the example):
var request = { url: 'http://myIP:8080/sc.eco/servlet/chat/',
contentType : "application/json",
logLevel : 'debug',
transport : 'websocket' ,
trackMessageLength : true,
fallbackTransport: 'long-polling'};
request.onOpen = function(response) {
content.html($('<p>', { text: 'Atmosphere connected using ' + response.transport }));
input.removeAttr('disabled').focus();
status.text('Choose name:');
};
It's shown on the console "Websocket successfully opened":
but it's stacked in this request:
Request URL:ws://myIP:8080/sc.eco/servlet/chat/?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=2.2.1-jquery&X-Atmosphere-Transport=websocket&X-Atmosphere-TrackMessageSize=true&X-Cache-Date=0&Content-Type=application/json&X-atmo-protocol=true
Request Method:GET
Status Code:101 Switching Protocols
¿Any idea? :S
I had the same problem. I could resolve this by setting enableProtocol to false in the request config.
In your case this would look like this:
var request = { url: 'http://myIP:8080/sc.eco/servlet/chat/',
contentType : "application/json",
logLevel : 'debug',
transport : 'websocket' ,
trackMessageLength : true,
fallbackTransport: 'long-polling',
enableProtocol: false };
I came to this solution was originally proposed in this thread.