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
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:
bash
Copy code
mkdir my-project
cd my-project
npm init -y
npm install express mongoose cors
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}`);
});
'mongodb://localhost:27017/mydatabase'
with your MongoDB connection string./item
will return data from MongoDB based on the provided token.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>
'http://localhost:3000/item?token=XXX'
with the URL of your server and the appropriate token.<h1>
element.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.