getting error message while try to load mapbox getting error message while try to load mapbox express express

getting error message while try to load mapbox


I bumped into this issue today. I know you might have been answered now. But still below is your answer : Credits Donglin-

https://www.udemy.com/course/nodejs-express-mongodb-bootcamp/learn/lecture/15065656#questions/12020720

Sending CSP headers to allow scripts from mapbox to be loaded. Sample below :

exports.getTour = catchAsync(async (req, res, next) => {  const tour = await Tour.findOne({ slug: req.params.slug }).populate({    path: 'reviews',    fields: 'review rating user'  });  res    .status(200)    .set(      'Content-Security-Policy',      "default-src 'self' https://*.mapbox.com ;base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src https://cdnjs.cloudflare.com https://api.mapbox.com 'self' blob: ;script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests;"    )    .render('tour', {      title: `${tour.title} Tour`,      tour    });});


In response to the initial question by @Veera, I believe you encountered this problem when taking the course: Node.js, Express, MongoDB & More: The Complete Bootcamp

As mentioned earlier, it is a CSP-Content Security Policy that prevents browsers from loading content (images, scripts, videos etc) from unsupported sources.

You can solve this problem by adding api.mapbox.com as a supported source in your project. The code below is my router file for handling routes that make use of Mapbox.

const express = require('express');const viewController = require('../controllers/viewController');const CSP = 'Content-Security-Policy';const POLICY =  "default-src 'self' https://*.mapbox.com ;" +  "base-uri 'self';block-all-mixed-content;" +  "font-src 'self' https: data:;" +  "frame-ancestors 'self';" +  "img-src http://localhost:8000 'self' blob: data:;" +  "object-src 'none';" +  "script-src https: cdn.jsdelivr.net cdnjs.cloudflare.com api.mapbox.com 'self' blob: ;" +  "script-src-attr 'none';" +  "style-src 'self' https: 'unsafe-inline';" +  'upgrade-insecure-requests;';const router = express.Router();router.use((req, res, next) => {  res.setHeader(CSP, POLICY);  next();});router.route('/').get(viewController.getOverview);router.route('/tour/:slug').get(viewController.getTour);router.route('/login').get(viewController.getLoginForm);module.exports = router;


This particular error is a CSP error that I personally have answered on the git repo as well as the udemy lecture..Nonetheless here it goes again for the Stackoverflow version :)

Add the following code to you app.js

app.use((req, res, next) => {  res.setHeader(    'Content-Security-Policy',    "script-src  'self' api.mapbox.com",    "script-src-elem 'self' api.mapbox.com",  );  next();});