首页 > 解决方案 > 无法使用带有哈巴狗的 mapbox 显示地图

问题描述

在此处输入图像描述

正如上面显示的标题和图片,我在我的网站上显示地图时遇到了问题。我四处寻找解决方案,但没有一个与我的相似。需要注意的一件事是我正在使用 pug(用 HTML 编写 JS 的模板)。这是下面显示的JS的代码

/* eslint-disable */
const locations = JSON.parse(document.getElementById("map").dataset.locations);

mapboxgl.accessToken = 'xxxxxx';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'xxxxxxx',
    center: [-118.315192, 34.006905],
    zoom: 10
});

这是我用来实现在我的网站上显示地图的顶级代码的代码。

    section.section-map
        //- Data-location set in dataset in mapbox.js
        #map(data-locations=`${JSON.stringify(tours.locations)}`)

这是我的主要内容

doctype html
html
    head
        block head
            meta(charset='UTF-8')
            meta(name='viewport' content='width=device-width, initial-scale=1.0' value="script-src 'self' api.mapbox.com;")
            title Natours | #{tours.name} Tour
            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')

    body
        // HEADER

        include _header
        
        // CONTENT

        block content
            h1 This is a placeholder heading

        // FOOTER

        include _footer
            script(src="/js/mapbox.js")

标签: javascriptnode.jspugmapbox

解决方案


您在标题上设置的内容安全策略似乎有问题..

在元标记内添加以下代码。

script-src 'self' api.mapbox.com;

了解更多信息阅读内容安全政策

因为 OP 使用第三方 npm 模块helmet...

现在您可以按以下方式禁用头盔中的 CSP..

app.use(
  helmet({
    contentSecurityPolicy: false,
  })
);

更多阅读文档Helmet Docs


推荐阅读