#moez-corp-error
1 messages · Page 1 of 1 (latest)
Hello! What is the CORS policy you have configured on your backend? Is it possible you have Cross-Origin-Embedder-Policy set?
hi @mint wind I just set cors() as a middleware in my server file like so:
const app = express();
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
// 1) GLOBAL MIDDLEWARES
app.use(cors());
// Serving static files
app.use(express.static(path.join(__dirname, './public')));
// Development logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// ENHANCE APPLICATION SECURITY - Set security HTTP headers
app.use(helmet({
contentSecurityPolicy: false,
}));
// ENHANCE APPLICATION SECURITY - Limit requests from same API
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour!'
});
app.use('/api', limiter);
// Body parser, reading data from body into req.body
app.use(express.json({ limit: '10kb' }));
app.use(express.urlencoded({ extended: true, limit: '10kb' }));
app.use(cookieParser());
// ENHANCE APPLICATION SECURITY - Data sanitization against NoSQL query injection
app.use(mongoSanitize());
// ENHANCE APPLICATION SECURITY - Data sanitization against XSS
app.use(xss());
// ENHANCE APPLICATION SECURITY - Prevent parameter pollution
app.use(
hpp({
whitelist: [
'duration',
'ratingsQuantity',
'ratingsAverage',
'maxGroupSize',
'difficulty',
'price'
]
})
);
// Test middleware
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
//console.log(req.cookies);
next();
});
// 3) ROUTES
app.use('/', viewsRouter);
app.use('/api/v1/travels', travelRouter);
app.use('/api/v1/users', userRouter);
app.use('/api/v1/ratings', ratingRouter);
app.use('/api/v1/bookings', bookingRouter);
// Handle any request that beyond the above routes
app.all('*', (req, res, next) => {
next(new ErrHandlingClass(`Can't find ${req.originalUrl} on this server!`, 404));
});
// If there is any request reach this point it will handled by the global error controller
app.use(globalErrorHandler);
module.exports = app;
I'm confused if I have to set cors from the backend code or the frontend fetching api
Thanks for sending over that code! I think I see the issue - your integration is using helmet (as you can see in the below excerpt from your code
app.use(helmet({
contentSecurityPolicy: false,
}));
Helmet made a change to enable the Cross-Origin-Embedder-Policy header by default, which doesn't work with Stripe.js. You need to disable it like this:
app.use(
helmet({
crossOriginEmbedderPolicy: false,
// ...
})
);
You can read more about this here: https://github.com/helmetjs/helmet/issues/343#issuecomment-1006259994
it should be like that right ?
app.use(helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false
}));
yup!
it keeps the same error
Have you made sure to re-deploy? From what I can see, that would be the only thing in your code that would be setting the cross-origin-embedder-policy header that would cause this error
the console log this error now:
Feature Policy: Skipping unsupported feature name “payment”.
I restart my server I'm still work in dev environment
The "Feature Policy" log you can ignore for now - are you still getting the Cross-Origin-Resource-Policy header error?
yes
That's strange - I'd suggest slowly commenting out parts of your middleware to pinpoint which specific line is causing this header to be set. Once you know which line is causing the error, we can find a way to fix it
which middleware you suggest to comment out
Really anything that could be cors related
ok
hey @mint wind it works
I commented out helmet and express-rate-limite middlewares
👍 Awesome - does it still work if you leave helmet commented out but add the express-rate-limite middleware back in?
now I have parcel error
I tried to restart my server manually without using nodemon in order to get the change effects faster but it runs in parcel error now
Uncaught
Exception { name: "NS_ERROR_CONTENT_BLOCKED", message: "", result: 2153644038, filename: "http://127.0.0.1:3000/js/bundle.js", lineNumber: 9575, columnNumber: 0, data: null, stack: "parcelRequire<[\"../../node_modules/parcel-bundler/src/builtins/hmr-runtime.js\"]<@http://127.0.0.1:3000/js/bundle.js:9575:12\nnewRequire@http://127.0.0.1:3000/js/bundle.js:47:24\nparcelRequire<@http://127.0.0.1:3000/js/bundle.js:81:17\n@http://127.0.0.1:3000/js/bundle.js:120:3\n" }
and this one:
Content Security Policy: The page’s settings blocked the loading of a resource at https://js.stripe.com/v3/ (“script-src”).
ok it works without helmet now
any work around to disable cross-origin policy in helmet module?
From what I see in their github repo, that suggestion I gave earlier to set crossOriginEmbedderPolicy: false should have worked. If you can get it to work, I'd suggest asking for help from helmet on how to disable it
let restart my server using "crossOriginEmbedderPolicy: false" as helmet option, adn tell you, just a second please
it works with helmet like that:
app.use(helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false
}));
but from the browser console (firefox) there are manu errors, looks like handled erros, let me show you
error1:
Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”). Source: (function() {
document.__defineSetter__("cookie", function(/*value*/) { });
document.__defineGetter__("cookie", function() { return ""; });
// trim referrer down to origin
let referrer = document.referrer;
if (referrer) {
referrer = referrer.slice(
0,
referrer.indexOf('/', referrer.indexOf('://') + 3)
) + '/';
}
document.__defineGetter__("referrer", function () { return referrer; });
})();.
error2:
Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”). Source: (function() {
/*
* If localStorage is inaccessible, such as when "Block third-party cookies"
* in enabled in Chrome or when `dom.storage.enabled` is set to `false` in
* Firefox, do not go any further.
*/
try {
// No localStorage raises an Exception in Chromium-based browsers, while
// it's equal to `null` in Firefox.
if (null === localStorage) {
throw false;
}
} catch (ex) {
return;
}
let lsProxy = new Proxy(localStorage, {
set: function (/*ls, prop, value*/) {
return true;
},
get: function (ls, prop) {
if (typeof ls[prop] == 'function') {
let fn = function () {};
if (prop == 'getItem' || prop == 'key') {
fn = function () { return null; };
}
return fn.bind(ls);
} else {
if (prop == 'length') {
return 0;
} else if (prop == '__proto__') {
return lsProxy;
}
return;
}
}
});
Object.defineProperty(window, 'localStorage', {
configurable: true,
enumerable: true,
value: lsProxy
});
})().
and:
Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”). Source: (function (NAVIGATOR, OBJECT) {
if (NAVIGATOR.doNotTrack != "1") {
OBJECT.defineProperty(OBJECT.getPrototypeOf(NAVIGATOR), "doNotTrack", {
get: function doNotTrack() {
return "1";
}
});
}
if (!NAVIGATOR.globalPrivacyControl) {
try {
OBJECT.defineProperty(NAVIGATOR, "globalPrivacyControl", {
value: true
});
} catch (e) {
console.error("Privacy Badger failed to set navigator.globalPrivacyControl, probably because another extension set it in an incompatible way first.");
}
}
// save locally to keep from getting overwritten by site code
}(window.navigator, Object));. moz-extension:33:9
it seems like we don't use the proper way, right?
I tried with chrome no errors in browser console, I think I leave it like that for and I'll try tomorrow to go deep in documentation in helmet CORS in order to understand more how it works
thank you for your help! I really appreciated @mint wind
👋 Glad we could at least solve that initial error! CORS isn't my strong suit either, so it always take a bit longer to get an answer