getting error message while try to load mapbox
Asked Answered
A

7

5

mapboxgl.accessToken = 'xxxxxxxx';

var map = new mapboxgl.Map({
  container: 'map', // container ID
  style: 'mapbox://styles/mapbox/streets-v11', // style URL
});
doctype html
html
  head
    block head
      meta(charset='UTF-8') 
      meta(name='viewport' content='width=device-width, initial-scale=1.0')
      link(rel='stylesheet' href='/css/style.css')
      link(rel='shortcut icon', type='/image/png' href='/ img/favicon.png')
      link(rel='stylesheet', href='https://fonts. googleapis.com/css?family=Lato:300,300i,700')
      title Natours | #{title} 


  body
      //- HEADER 
      include _header

      //- CONTENT
      block content
        h1 this is a placeholder heading

      //- FOOTER
      include _footer
      
      script(src='/javascript/mapbox.js')

Refused to load the script 'https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Amando answered 16/3, 2021 at 7:47 Comment(0)
E
8

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
    });
});
Excruciation answered 8/5, 2021 at 20:58 Comment(0)
D
4

I also encountered the same error but after some research, I got a way around it.

Another way is to reconfigure helmet for securing http header.

Add the following code to your app.js file:

const scriptSrcUrls = [
  'https://api.tiles.mapbox.com/',
  'https://api.mapbox.com/',
];
const styleSrcUrls = [
  'https://api.mapbox.com/',
  'https://api.tiles.mapbox.com/',
  'https://fonts.googleapis.com/',
];
const connectSrcUrls = [
  'https://api.mapbox.com/',
  'https://a.tiles.mapbox.com/',
  'https://b.tiles.mapbox.com/',
  'https://events.mapbox.com/',
];
const fontSrcUrls = ['fonts.googleapis.com', 'fonts.gstatic.com'];
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: [],
      connectSrc: ["'self'", ...connectSrcUrls],
      scriptSrc: ["'self'", ...scriptSrcUrls],
      styleSrc: ["'self'", "'unsafe-inline'", ...styleSrcUrls],
      workerSrc: ["'self'", 'blob:'],
      objectSrc: [],
      imgSrc: ["'self'", 'blob:', 'data:'],
      fontSrc: ["'self'", ...fontSrcUrls],
    },
  })
);

Make sure to remove the following piece of code which is initially in your app.js file:

app.use(helmet());
Disturbing answered 1/4, 2022 at 9:27 Comment(0)
H
3

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;
Hypercriticism answered 1/10, 2021 at 11:17 Comment(0)
B
1

if you are using helmet then this might solve your issue

app.use(helmet.ContentSecurityPolicy());
Bdellium answered 25/4, 2022 at 17:22 Comment(0)
L
1

If you are using helmet middleware to configure your headers, I will recommend the following line of code:

app.use(helmet.crossOriginResourcePolicy({ policy: 'cross-origin' }));
Liddell answered 17/11, 2022 at 13:16 Comment(1)
OK, this did it for me. I really cannot say how happy this made me. I obviously need to learn a bit more about security, helmet, and not just getting beat up about CORS issues. TY!Dose
T
0

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();
});
Terriss answered 8/5, 2021 at 21:4 Comment(1)
Fix the typo pleaseBelloc
R
0

If u use helmet follow this:

app.use(
helmet({
    contentSecurityPolicy: false,
    crossOriginEmbedderPolicy: false,
  })
);
Rheumatoid answered 22/5, 2022 at 8:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.