1

What is the easiest way for me to set the content security policy for a new form I am using? I have a frontend to backend form working for my registration but this form is a lot more complicated and is throwing me the errors below. I am aware this is to do with webpack and I have tried inserting code into my publ;ic index.html file which just stopped the page from rendering.

enter image description here

enter image description here

Would this have anything to do with my CORS settings in the backend? I have the below code which references headers and the I have been getting error messages about setting headings in other forms that I am having the same issues with.

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header(
        'Access-Control-Allow-headers',
        'Origin, X-Requested-With, Content-Type, Accept',
    );
    next();
});
James Gee
  • 129
  • 1
  • 3
  • 24

1 Answers1

1

The errors described have nothing to do with your CORS settings in the backend. They are related to CSP (Content-Security-Policy) header, which you, it would seem, do not use. But for nonexistent pages node JS is published CSP header on its own.

Pay attention to status code 404 Not Found. If you do not handle this kinds of errors, nodeJS uses own finalhandler to carry out of those by default.
Last versions of this finalhandler publish the CSP default-src 'none'; all the nitty-gritty is here.

Looks like you do not serve routes to root / folder in you server config, therefore /favicon.ico and similar urls are not found -> finalhandler publishes default-src 'none'; -> you observe CSP violation in the browser console (along with the 404 not found messages).

You have to add into server.js something like that:

app.use(express.static('client/public'));
app.get("/favicon.ico", (req, res) => {
  res.sendFile(path.resolve(__dirname, "/favicon.ico"));
});

The above will solve the issue with "/favicon.ico Not Found", for other "non existent" Urls you need to add routes too.

granty
  • 7,234
  • 1
  • 14
  • 21
  • Cheers, for the static url address do I direct it to the location from the server.js file in my backend? – James Gee Mar 31 '21 at 21:00
  • Yes, default file name for start app should be `server.js` if you did not redefine it. And have a look, at least breefly, [Routing in Express](https://expressjs.com/en/guide/routing.html) and [Custom static routing Express](https://stackoverflow.com/questions/36395563/static-routing-in-node-express). May be you'll find a better examples how to make routing. – granty Apr 01 '21 at 14:32