javascriptnode.jsaxiosparcel

Parcel 2 - Uncaught Error: Cannot find module 'axios'


I am doing an udemy course, 'Node.js, Express, MongoDB & More'. In the course, the lecturer uses parcel v1, but since then parcel has created v2 and I am unable to install v1. I am trying to call the file from the dist file created from parcel, in my case is ./public/js/bundle and I keep getting two errors:

Refused to connect to 'ws://127.0.0.1:1234/' because it violates the following Content Security Policy directive: "default-src 'self' https://\*.mapbox.com". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Uncaught Error: Cannot find module 'axios'

this is my code:

base.pug:

doctype html
html 
    head
        block head 
            meta(charset="UTF-8")
            meta(name="viewport" content="width=device-width, initial-scale=1.0")
            title Natours | #{title}
            link(rel="stylesheet", href="/css/style.css")
            link(rel="shortcut icon" type="image/png" href="/img/favicon.png")
            link(href="https://fonts.googleapis.com/css?family=Lato:300,300i,700" rel="stylesheet")

    body 
        // HEADER
        include header
        
        // CONTENT
        block content
            h1 This is a placeholder heading

        // FOOTER
        include footer


    block scripts 
        script(type="module" src="/js/bundle/index.js")

index.js:

import '@babel/polyfill'
import { displayMap } from './mapbox';
import { login } from './login';

// DOM ELEMENTS
const mapbox = document.querySelector('#map');
const loginForm = document.querySelector('.form');

// DELEGATION
if (mapbox) {
  const locations = JSON.parse(mapbox.dataset.locations);
  displayMap(locations);
}

if (loginForm) {
  loginForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const email = document.querySelector('#email').value;
    const password = document.querySelector('#password').value;
    login(email, password);
  });
}

console.log('Hello from parcel');

login.js:

import axios from 'axios';
import { showAlert } from './alert.js';

export const login = async (email, password) => {
  console.log(email, password);
  try {
    const res = await axios({
      method: 'POST',
      url: 'http://127.0.0.1:3000/api/v1/users/login',
      data: {
        email,
        password,
      },
    });

    if (res.data.status === 'success') {
      showAlert('Logged in successfully');
      window.setTimeout(() => {
        location.assign('/');
      }, 1500);
    }
  } catch (err) {
    showAlert(`Error: ${err.response.data.message}`);
  }
};

mapbox.js:

export const displayMap = (locations) => {
  mapboxgl.accessToken = 'MY_TOKEN';

  var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/j-cet101/cll7vlp6l00oa01pd3pmu5r8r',
    scrollZoom: false,
  });

  map.addControl(new mapboxgl.NavigationControl());

  const bounds = new mapboxgl.LngLatBounds();

  locations.forEach((loc) => {
    // Create marker
    const el = document.createElement('div');
    el.className = 'marker';

    // Add marker
    new mapboxgl.Marker({
      element: el,
      anchor: 'bottom',
    })
      .setLngLat(loc.coordinates)
      .addTo(map);

    // Add popup
    new mapboxgl.Popup({
      offset: 30,
    })
      .setLngLat(loc.coordinates)
      .setHTML(`<p>Day ${loc.day}: ${loc.description}</p>`)
      .addTo(map),
      // Extend map bounds to include current location
      bounds.extend(loc.coordinates);
  });

  map.fitBounds(bounds, {
    padding: {
      top: 200,
      bottom: 150,
      left: 200,
      right: 200,
    },
  });
};

package.json commands:

"watch:js": "parcel watch ./public/js/index.js --dist-dir ./public/js/bundle",
"build:js": "parcel build ./public/js/index.js --dist-dir ./public/js/bundle"

I am not really sure why I am getting this errors or if I am missing some module or if is there something else that has been added to parcel v2 that is necessary to do that I am not aware of, so I would be grateful if someone could help with this one :)

NOTE: I already have all the necessary packages installed


Solution

  • I just solved the problem by adding

    "browserslist": "> 0.5%, last 2 versions, not dead"
    

    Source - https://parceljs.org/getting-started/webapp/#declaring-browser-targets

    To package.json and now I am able to do the login, view the map and the website is working fine, but I still am getting this error:

    Refused to connect to 'ws://127.0.0.1:1234/' because it violates the following Content Security Policy directive: "default-src 'self' https://*.mapbox.com". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.