Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJS & Express — Run index.js code from index.html

I’m learning NodeJS, Express via Replit.com with a small project. The goal is to create a simple input field that when submitted posts to various channels, such as Discord, Twitter, etc.

The below code runs on replit.com, loads the necessary packages and successfully connects to the Discord Channel.

I can run javascript code in app.js from the html. (Such as send()) Placing such function inside of index.js does not work. How do I access code from index.js (such as the methods from the discord js) to trigger/execute them from the html?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Directory Structure:

index.js
public/
  indx.html
  css/
    app.css
  js/
    app.js

index.js:

const express = require("express");
const path = require('path');
const app = express();

app.listen(3000, () => {
  console.log("project is running");
})

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    res.redirect('index.html');
});

const { Client, GatewayIntentBits, Intents } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
  ]
})

client.on("ready", () => {
  console.log("Bot is ready.");
  client.channels.cache.get('1056649564532252XXX').send('yo');
});

client.login(process.env.token);

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sample Site</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <style>
    body { padding-top: 50px; }
  </style>
</head>
<body>

  <div class="container">
    <input />
    <button onclick="send()">Send</button>
  </div>

   <script src="js/app.js"></script>

</body>
</html>

app.js:

function send() {
  console.log('sent');
  // this won't work here: client.channels.cache.get('1056649564532252XXX').send('yo');
}

>Solution :

You cannot use client variable because it’s defined in the server and send function is running on client browser.

So you need to make an ajax call back to the server and send the input data.

The server will run the message send process.

In index.js you need to add new endpoint to accept the ajax

app.post('/send', function(req, res) {
  client.channels.cache.get('1056649564532252XXX').send('yo')

  res.json({ success: true })
});

In app.js

function send() {
  console.log('sending');

  fetch('/send', { method: 'POST' })
    .then(response => response.json())
    .then(data => console.log('sent', data))
    .catch(error => console.error(error))
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading