Website = request info from database and dynamically replace text

How can I do something like:

fetch('https://website.com?token=XXX').then(function(response) {

to pull information from my mongoDB and update the text on a website with the response? Thanks in advance to all of you guys

To achieve the task of fetching data from a MongoDB database and updating the text on a website, you need a combination of server-side and client-side code. Here’s a step-by-step guide to accomplish this:

Server-Side (Node.js + Express)

  1. Set Up Your Node.js ServerFirst, ensure you have Node.js and npm installed. Create a new Node.js project and install the required dependencies:

bash

Copy code

mkdir my-project
cd my-project
npm init -y
npm install express mongoose cors
  1. Create a Simple Express ServerCreate a file named server.js and add the following code to set up your Express server and connect to MongoDB:

javascript

Copy code

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();
const port = 3000;

// Middleware
app.use(cors());
app.use(express.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Define a schema and model
const ItemSchema = new mongoose.Schema({
  text: String
});
const Item = mongoose.model('Item', ItemSchema);

// API route to get item
app.get('/item', async (req, res) => {
  const token = req.query.token;
  if (token === 'XXX') { // Validate token if needed
    try {
      const item = await Item.findOne(); // Fetch data from MongoDB
      res.json(item);
    } catch (err) {
      res.status(500).json({ error: 'Failed to fetch data' });
    }
  } else {
    res.status(403).json({ error: 'Invalid token' });
  }
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
  • Replace 'mongodb://localhost:27017/mydatabase' with your MongoDB connection string.
  • The API route /item will return data from MongoDB based on the provided token.

Client-Side (HTML + JavaScript)

  1. Create an HTML FileCreate an index.html file with a simple layout and a script to fetch data and update the text:

html

Copy code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Update Text from MongoDB</title>
</head>
<body>
  <h1 id="text">Loading...</h1>

  <script>
    // Fetch data from the server
    fetch('http://localhost:3000/item?token=XXX')
      .then(response => response.json())
      .then(data => {
        // Update the text on the website
        document.getElementById('text').textContent = data.text;
      })
      .catch(error => {
        console.error('Error fetching data:', error);
        document.getElementById('text').textContent = 'Failed to load data';
      });
  </script>
</body>
</html>
  • Replace 'http://localhost:3000/item?token=XXX' with the URL of your server and the appropriate token.
  • The script will fetch data from your server and update the text content of the <h1> element.

Summary

  1. Server-Side: Set up a Node.js server with Express to connect to MongoDB and provide an API endpoint.
  2. Client-Side: Use JavaScript fetch to get data from your API and update the website content dynamically.

Make sure to adjust the MongoDB connection string, token validation, and error handling according to your specific needs.