Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express and Cheerio/JSDOM

I am trying to get Cheerio to work with Express. I'd like to be able to manipulate the dom from the server, but all I have found is web scraping..

There are some requirements..

At the moment, I am able to run multiple app.listen(port); statements, and use multiple servers.

I'm trying to append <script>alert("test);</script> to every single page sent by express.

I've created the express server: (Assuming Path is a predefined variable)

var express = require('express');
var app = express();    
app.get('/', function (req, res) {
        app.use(app.static(Path));
        res.sendFile(Path + "/index.html");
    });
app.listen(Port);

Can you guys provide me with a working example to append this to the page. Is there a way to get this to work in real time?

Thanks!

like image 500
medemi68 Avatar asked Feb 28 '26 21:02

medemi68


1 Answers

Here's a quick/simple example with no error handling:

var express = require('express');
var fs = require('fs');
var cheerio = require('cheerio');

var app = express();

app.get('/', function (req, res) {
    fs.readFile(Path + '/index.html', function(err, data) {               
        var $ = cheerio.load(data);

        $('body').append('<script>alert("test");</script>');

        res.send($.html());
    });
 });

app.listen(Port);

I just tested that locally and it worked as expected. Be sure to test err inside the readFile callback in your real implementation and handle things appropriately if the file isn't found or there's an error reading it.

like image 96
Dave Ward Avatar answered Mar 03 '26 09:03

Dave Ward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!