What methods can I use to integrate Cheerio with CSS Manipulation?

I've been working on a web scraping project using axios, cheerio, and express. However, every time I attempt to run the project, it encounters errors.

For testing purposes, I am using a test page from my friend's website. Here is the code snippet I used:

const express = require('express')
const app = express()
const port = 3000
const publicDir = app.use(express.static('public'))
var cheerio = require('cheerio'); // A jQuery-like tool for node.js
const { replaceWith } = require('cheerio/lib/api/manipulation');
const axios = require('axios').default;


app.get('/', (req, res) => {
  res.render('/public/index.html')
})

app.get('/imagineoranges', (req, res) => {
  const $ = cheerio.load('/imagineoranges')
  axios.get("https://imagineoranges.neocities.org")
    .then(({data}) => res.send(data))
    .then( $('a:link').css("color: white;") )
    .then( $('a:visited').css("color: yellow;") )
    .then( $('a:hover').css("color: yellow;") )
    .then( $('body').css("@import url('https://fonts.googleapis.com/css2?family=Rubik&display=swap'); background-color: #ff7300; color: white; font-family: 'Rubik', sans-serif;") ) 
})


app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

However, when you run this code, the following error occurs:

node:internal/modules/cjs/loader:535
      throw e;
      ^

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/api/manipulation' is not defined by "exports" in /home/lucas/Desktop/UBlock/node_modules/cheerio/package.json
    at new NodeError (node:internal/errors:393:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:292:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:602:3)
    at resolveExports (node:internal/modules/cjs/loader:529:36)
    at Module._findPath (node:internal/modules/cjs/loader:569:31)
    at Module._resolveFilename (node:internal/modules/cjs/loader:981:27)
    at Module._load (node:internal/modules/cjs/loader:841:27)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/home/lucas/Desktop/UBlock/index.js:6:25) {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

Node.js v19.0.1

Answer №1

Make sure to pass the response HTML to Cheerio for manipulation before rendering it back to the user.

If you're looking to apply styles, consider using CSS instead by including a <style> tag.

Here is an example:

app.get("/oranges", async (req, res) => {
  try {
    const { data } = await axios.get("https://example.com", {
      responseType: "text",
    });
    const $ = cheerio.load(data);
    $("head").append(
      `<style type="text/css">@import url(https://fonts.googleapis.com/css2?family=Roboto&display=swap);a:link,body{color:#000}a:hover,a:visited{color:#00f}body{background-color:#ccc;font-family:Roboto,sans-serif}<style>`
    );
    res.set("content-type", "text/html").send($.root().html());
  } catch (err) {
    res.status(err.response?.status ?? 500).send(err.response?.data);
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use Ajax code to send data to a PHP page and receive the results as a JSON-encoded multidimensional array containing information on each item?

Apologies for the unconventional question title. What I am trying to accomplish is managing two tables in my database: a hotel table (table1) and a room type table (table2). My goal is to allow customers to customize their travel packages by changing hote ...

Storing Json Web Tokens in a mongodb database with node express

Recently, I integrated jwt (JsonWebToken) into my Node.js Express application with MongoDB. When generating the token, I saved the value in a database collection and retrieved it from MongoDB to pass on to subsequent pages. Additionally, I implemented a ...

Saving large data in NodeJS using MongoDB and Mongoose in a non-blocking manner

Currently, I am in the midst of developing a straightforward application utilizing NodeJS, ExpressJS (with EJS), MongoDB, and Mongoose. Here's a synopsis of the issue at hand that requires some recommendations: Situation 1) Triggered by a specific e ...

Create a new attribute within the ng-model object once it has been updated through ng-repeat

I am trying to figure out how to add a "discountRate" property to an ng-model object after it has been changed within an ng-repeat block. Check out this example for more information Another example can be found here Although the ng-model is updated as e ...

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Out of the box, Next.js is equipped with a standard error message stating: "TypeError: Cannot read properties of null (reading 'useContext')"

After just setting up next.js for my upcoming website, I ran into some unexpected errors while trying to host it with "next". The specific error message I encountered was: TypeError: Cannot read properties of null (reading 'useContext') This iss ...

Implementing precise search functionality in a table with jquery datatables

Hey there, I'm attempting to implement an exact search feature in jQuery datatables. In my table, I have a column called "status" with values of either "paid" or "unpaid". Currently, when I type "unpaid", it correctly displays only the unpaid record ...

JavaScript for rotating an element upon button click

My webpage design <div id="yabanner"> <img src="img/ok.jpg"> </div> <button>Click Me</button> <button>Click Me</button> <button>Click Me</button> My script code var button = document.getElementsBy ...

What could be causing the slowdown in my NodeJS IRC-bot?

Decided to challenge myself today by creating an IRC-bot using JavaScript with NodeJS. So far, everything is functioning correctly, but it seems like there may be a bottleneck somewhere. For instance, when I input a command multiple times, the initial res ...

Struggling to display flash messages while utilizing connect-flash with a Node/Express application

I have encountered an issue while trying to display flash messages with connect-flash after users successfully log in to my app. Although I am able to see the flash messages in the console log, they do not appear on the client side. Interestingly, when I ...

What is the best way to design a navigation bar for a one-page application using Vue?

Currently, I am developing a Vuejs single-page application and I'm exploring ways to implement a navbar that can toggle the visibility of different sections within the app upon clicking. While I have successfully designed the navbar layout, I am encou ...

Methods to prompt a user to select an option using Bootstrap

I have been struggling with this problem for hours and it's really starting to frustrate me! Currently, I am incorporating Twitter Bootstrap along with bootstrap-min.js. This is the code snippet in question: <select id="assettype" name="assettyp ...

Combine, condense, and distribute JavaScript files using Express without applying gzip compression to the response

Currently, I am developing a web application using Express. My goal is to merge, minify, and serve .js files efficiently. To achieve this, I have created a middleware with the following code: var fs = require('fs'), path = require('path ...

Is there a way to implement infinite scrolling in my MUI DataGrid component?

Hey there! I have a custom component that needs to have infinite scrolling added to it. I tried looking into MUI DataGrid for solutions, but didn't have much luck implementing anything successfully. Currently, I'm fetching data using GraphQL and ...

The price filter slider is experiencing issues with the onresize function not functioning properly

I am facing an issue with a price filter I developed for my project. Despite having coded it, the filter is not functioning properly. <div class="price_range_caption"> <span class="currency_from">Rs.</span><span id="price_range_f ...

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

Deciphering JSON information extracted from a document

I am currently working on a Node JS project where I need to read a file containing an array of JSON objects and display it in a table. My goal is to parse the JSON data from the array. Below is a sample of the JSON data: [{"name":"Ken", "Age":"25"},{"name" ...

Object Literal vs Object-Oriented Javascript: Comparing the Two

When it comes to using Object-Oriented Programming (OOP) in JavaScript, I often find myself not utilizing it much. For instance, instead of defining a constructor function and setting up prototypes like this: function Person(name){ return this.name = name ...

No data returned from API call in Next.js and Strapi

Recently, I encountered an issue with my Next.js frontend application that fetches data from a Strapi backend. Despite seeing requests being made in the Strapi developer logs, the retrieved data is empty. Below is a snippet of my Next.js code: import { us ...

Tips on displaying a particular JSON attribute?

After starting with a JSON string, attempting to convert it into a JSON object and then trying to print a specific field (such as firstName), I am getting undefined. What could be the issue here? Thank you for your help! var string = '{"firstName ...