I am working on a nodejs and express project, using mongodb as a database, and am trying to use axios in that project. My setup is to use .pug for the rendering of the frontend but now I seem the have a problem importing the axios library in the frontend javascript code.
In the browser console is an error: Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../".
My file structure is (only including relevant files):
public
|-- js
|-- index.js // here I want to use axios but it does not work
views
|-- base.pug // I have many other .pug files here
package-lock.json
package.json
app.js
server.js
I have installed axios with npm and it comes up as a dependency in package.json.
In the index.js file I have used both:
import axios from 'axios';
and:
const axios = require('axios');
I have also tried to use a reference in the base.pug file, both in the header and the footer but that does not work either. There I tried to use these references:
script(src='https://cdnjs.cloudflare.com/ajax/libs/axios/0.23.0/axios.min.js')
and:
script(src='https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js')
I have not been bundling the .js code for the frontend.
Any thoughts on how to fix this?
I was able to find the solution for my own problem :)
Since I could not import axios in the index.js file I used the script tag in the base.pug file.
The problem was that I am using the npm library helmet and in version 4 and later helmet sets as default very strict Content Security Policy. To fix that I had to set helmet up in the app.js file like this:
app.use(
helmet({
contentSecurityPolicy: false,
})
);
With this setup I can set my own Content Security Policy. When I had made these changes though I got a new error regarding CORS: "Access to XMLHttpRequest at 'http://127.0.0.1:3000/***' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
To fix this CORS error I installed another npm package named 'cors':
npm install --save cors
Then in the app.js file used it like this:
const cors = require('cors');
and finally:
app.use(cors({ origin: '*' }));
The final setup for the cors part might be to generally set up but it works for me as of now. I will though read through the documentation and see if there is a better set up to be used.