I am trying to complete some web scraping projects and I keep running into the same error which is as follows:
import axios from 'axios'
^^^^^^
SyntaxError: Cannot use import statement outside a module
The Javascript code is below:
import axios from "axios";
import Cheerio from "cheerio";
import Express from "express";
const PORT = process.env.PORT || 5000;
const app = express();
axios("https://www.manchestereveningnews.co.uk/sport/football/")
.then((res) => {
const htmlData = res.data;
const $ = cheerio.load(htmlData);
const articles = [];
$(".teaser", htmlData).each((index, element) => {
const title = $(element).children("headline").text();
const titleURL = $(element).children("headline").attr("href");
articles.push({
title,
titleURL,
});
});
console.log(articles);
})
.catch((err) => console.error(err));
app.listen(PORT, () => console.log("server is listening on port ${PORT}"));
Then there is the package.json here:
{
"name": "scrapy",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^1.1.3",
"cheerio": "^1.0.0-rc.12",
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
can anyone explain why I keep getting this same error and how to fix it?
I tried adding "Type": "Module", to the package.json file in multiple projects but that did not solve the issue, this was highly suggested online but did not work for me.