"Integrate information from a Node.js source into an already existing HTML document

I am new to node.js and have a question regarding my server.js file:

var express = require('express');
var cors = require('cors');
var app = express();
var path = require('path');
var request = require('request');
var cheerio = require("cheerio");

request({
  uri: "http://ptnpnh.ua",
}, function(error, response, body) {
  var $ = cheerio.load(body);

  $("[data-tab=toDay] .weatherNow .temp .temperature_value").each(function() {
    var link = $(this);
    var text = link.text();
    console.log(text);
  });
});

app.use(cors());

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
      res.sendFile(path.join(__dirname + '/index.html'));
    app.use(express.static('public'));
    app.use("/css", express.static(__dirname + '/css'));
    app.use("/color", express.static(__dirname + '/color'));
    app.use("/fontaw", express.static(__dirname + '/font-awesome'));
    app.use("/fonts", express.static(__dirname + '/fonts'));
    app.use("/img", express.static(__dirname + '/img'));
    app.use("/js", express.static(__dirname + '/js'));
    app.use("/node", express.static(__dirname + '/node_modules'));
});

app.post('/', function(req, res, next) {
});
app.listen(8080);

Is there a way for me to update the code in order to insert the "text" string into an existing dom element with id="appendedText" within the "/index.html" file?

Answer №1

you almost nailed it

const express = require('express');
const cors = require('cors');
const app = express();
const path = require('path');
const request = require('request');
const cheerio = require("cheerio");
const fs = require('fs'); // take note of this

request({
  uri: "http://ptnpnh.ua",
}, function(error, response, body) {
  const $ = cheerio.load(body);

  $("[data-tab=toDay] .weatherNow .temp .temperature_value").each(function() {
    const link = $(this);
    const text = link.text();
    console.log(text);
  });
});

app.use(cors()); 

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// static file paths
app.use(express.static('public'));
app.use("/css", express.static(__dirname + '/css'));
app.use("/color", express.static(__dirname + '/color'));
app.use("/fontaw", express.static(__dirname + '/font-awesome'));
app.use("/fonts", express.static(__dirname + '/fonts'));
app.use("/img", express.static(__dirname + '/img'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/node", express.static(__dirname + '/node_modules'));


app.get('/', function(req, res, next) { 

    fs.readFile(__dirname + '/index.html', 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        
        const $ = cheerio.load('<h2 class="title">Hello world</h2>')
        $('h2.title').text('Hello there!')
        $('h2').addClass('welcome')    

        res.set('Content-Type', 'text/html; charset=utf-8');
        res.send($.html());
    });
});

app.post('/', function(req, res, next) {

});
app.listen(8080);

Answer №2

If search engine optimization is not a concern for your website, and you want to avoid modifying the file every time dynamically (e.g. using cheerio), consider using JSONP.

Implementing JSONP

Add this code to your index.html

<head>
    ...
  <script>function getServerData(data) { window.__SERVER_DATA__ = data; }</script>
  <script src="/api/server-data.json?callback=getServerData"></script>
</head>

Define the following in your Node Express routes setup

const app = express();

// ...

app.get('/api/server-data.json', (req, res) => {
  res.jsonp({
    foo: 'foo',
    bar: 'bar'
  });
});

You can now access window.__SERVER_DATA__ from any part of your application to populate the DOM as needed.

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

initiating a server with pm2

When attempting to run a server on production using pm2, I am encountering the following issue in the logs: The command used with pm2 is: pm2 start dist/index.js --name myapp -- --fairos Logs show: 0|myapp | Not a valid group or command: --fairos Doe ...

npm release error: Out of memory - JS Allocation failed due to process overload

After numerous attempts, here is the outcome of my efforts to publish using npm: An error occurred in ../deps/v8/src/handles.h, line 48 CHECK(location_ != NULL) failed ==== C stack trace =============================== 1: V8_Fatal 2: v8::String::NewEx ...

I am looking to display only the date from req.body.date, excluding the time and time zone

Being a complete novice in Nodejs, I am currently working on developing a CRUD-based scheduling application to showcase user-created schedules along with their respective dates. However, the issue I am facing is that when using req.body.date, the date disp ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Guidelines for configuring an Android Socket.io client?

Once I've set up my SOCKET.IO server for a multi-room chat application, what is the best approach to developing the Android client using https://github.com/socketio/socket.io-client-java? I've done extensive research and have yet to find current ...

Having trouble getting a ForEach loop to work within promises when using mongoose?

Hey everyone! I'm diving into the world of nodeJs and working on a project that involves pushing certain values into an array. Unfortunately, my code isn't behaving as expected, and I suspect it has something to do with promises. Here's the ...

I'm having trouble with my code not fitting all screen resolutions. I usually code on a Macbook, but recently switched to a Windows computer and now everything is out of whack

$(function(){ $("#Welcome").typed({ strings: ["PROGRAMMERS / NETWORKERS"], typeSpeed: 60 }); }); html { background-color: mintcream; background-size: 100%; } /* Home */ .homeheader button { background-color: #4CAF450; top: ...

CSS3 animation for rotating elements

If I have this box in CSS3 (also if, for what I understand, this is not CSS3, just browsers specific) : HTML <div id="container"> <div id="box">&nbsp;</div> </div> ​ CSS Code #container { paddin ...

To show the image along with the .titleclass, .subtitleclass, and .description when clicking on it, what steps do I

<?php while($galleryrec = mysqli_fetch_array($getresultgallery)){ ?> <div class="col-lg-2 col-md-2 mb-4 mb-lg-0" id="imageidback"> <img data-id ="<?php echo $galleryrec['publishid& ...

Is it possible to replace text with a loader.gif?

<?php wp_enqueue_script( 'jquery'); ?> <script> jQuery(document).ready(function () { // ajax pagination jQuery('#navigation a').live('click', function () { // if not using wp_pagination, change ...

Distinguish individual elements within JSON from each other

Despite my limitations in altering the server-side code that generates this JSON: [ { test_id: "1", test_name: "Diagnostic Test 1" }, { test_id: "2", test_name: "Test 1" }, { test_id: "3", test_name: "Test 2" } ] I am ...

Incorrect Display of Datepicker Position

Trying to display a datepicker in a modal, but the output is not as expected: The datepicker is appearing in the wrong place. However, it works fine when testing on jsfiddle. Here is the link: http://jsfiddle.net/alverhothasi/D7bBg/ Currently using the ...

Extract the content from a <Span> element without specifying its ID

Is there a way to make it so that when a user clicks on an HTML tag, the text is copied to their clipboard? I also need to ensure that this functionality does not apply to a specific tag ID/name as I am unable to add those to my span. Is there a way to aut ...

What is the process for programmatically importing a module into the local scope in Node.js?

The coding environment is using a browser and the bundle tool being used is webpack. In my router.js file, I have the following code: import foo from './views/foo.vue' import bar from './views/bar.vue' import zoo from './views/zoo. ...

Retrieve MQTT messages via AJAX in web polling

Novice in the field. I'm attempting to create a straightforward data flow: MQTT-Data-source ---> MQTT Broker ---> NodeJS-MQTT-Client ---> AJAX-on-web-browser (fetching-every-3-seconds) I aim to retrieve the MQTT message and display it in the AJAX ...

Trouble arises when trying to configure webpack and install npm packages on Ubuntu systems

Recently, I encountered a sudden issue in my project that caused it to repeat and crash in Chrome: https://i.stack.imgur.com/pkVlA.png To resolve the issue, I decided to downgrade some of my packages and also downgraded my npm version to 6.6.0 which prov ...

JQuery animation with a delay using the delay() method

I am looking to implement a straightforward animation with jQuery by adding a CSS class to an h1 element and then removing it after 100 milliseconds. Could you kindly explain why the following code snippet might not function as expected? $("h1").addClass ...

Enhancing Function Calls for Better Performance in V8

Is V8 capable of optimizing repeated function calls with identical arguments? For instance, in the code snippet below, Variance is invoked twice with the same arguments. var Variance = require('variance'); function summary(items) { ...

Occasional Incomplete POST Data in sails.js

On my production server (ubuntu), there is a form that users fill out and submit to create or update records. Occasionally, when I use req.allParams(), the data object returned is incomplete. Typically, this is what I receive: data: { id: '58155 ...

Trying to convert <image> from canvas to png or base64 is not functioning properly

Currently, I am dealing with a grid div element that contains various HTML tags such as <div>, <p>, and <img>. I need to convert this grid to canvas and then encode it to base64 for saving on the server using PHP. Can someone assist me i ...