I’m a new developer, was following this tutorial, but got stuck at 21:06 when I was trying to fetch from local host after implementing the CORS. According to the video, it is supposed to work but I got this error instead.
fetch('http://localhost:3000');
VM262:1 Refused to connect to 'http://localhost:3000/' because it violates the following Content Security Policy directive: "connect-src chrome://resources chrome://theme 'self'".
(anonymous) @ VM262:1Understand this error
VM262:1 Refused to connect to 'http://localhost:3000/' because it violates the document's Content Security Policy.
(anonymous) @ VM262:1Understand this error
PromiseĀ {<rejected>: TypeError: Failed to fetch
at <anonymous>:1:1}
VM262:1 Uncaught (in promise) TypeError: Failed to fetch
at <anonymous>:1:1
Here is a summary of my code from the tutorial so far. I added the http headers to modify the CSP but still to no avail.
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const path = require('path');
const {logger} = require('./middleware/logger');
const errorHandler = require('./middleware/errorHandler');
const cookieParser = require('cookie-parser');
const cors = require('cors');
// Middleware to set CSP headers
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy', "default-src 'self'; connect-src 'self' http://localhost:3000");
next();
});
app.use(cors());
app.use(logger);
app.use(express.json());
app.use(cookieParser());
app.use('/', express.static(path.join(__dirname, '/public')));
app.use('/', require('./routes/root'))
app.all('*', (req, res) => {
res.status(404);
if (req.accepts('html')){
res.sendFile(path.join(__dirname, '/views/404.html'));
} else if (req.accepts('json')){
res.send({error: 'Not found'});
} else {
res.type('txt').send('Not found');
}
})
app.use(errorHandler);
app.listen(PORT, ()=>{
console.log(`Server is running on port ${PORT}`);
})
Does anyone know why is this occuring and how can I fix this problem? I tried searching for solutions online but the problems don’t seem to match mine as they are more advanced. Thanks.