Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

javascript - Re-Render EJS template in express node js

So I am using discord.js along with express and I want my webpage to update whenever the client.on("message") is fired. As far as I know and from research the only way possible to render a ejs template was on a get request, so how should I go about this.

this is my index.js

const express = require("express")
const https = require('https')
const Discord = require('discord.js')
const config = require('./config.json')
const app = express()
const bodyParser = require("body-parser")
app.set("view engine", "ejs")
app.use(express.static("public"))

const client = new Discord.Client();

client.on("message", function(message) { 
    console.log(message.author.username + " : "+ message.content)    
    // I want a res.render("index", {data : message.author.username + " : "+ message.content })       //equivalent here           
}); 

app.get('/', (req, res) => {
    res.render("index", {data : "EMPTY"}) 
})


app.listen(8000, () => {
    console.log("Running")
})

client.login(config.BOT_TOKEN);
question from:https://stackoverflow.com/questions/65861380/re-render-ejs-template-in-express-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This can be done using socket.io First install socket.io npm i socket.io Then update your application to use the socket.io engine.

const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const Discord = require('discord.js')
const config = require('./config.json')
const bodyParser = require("body-parser")

Update "index" file. Make sure the text your trying to update has id="count".

    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
      socket.on('count', function(data){
        $('#count').html(data.count);
      });
    </script>

Now finally update command.

client.on("message", function(message) { 
    console.log(message.author.username + " : "+ message.content)
    data = message.author.username + " : "+ message.content
    io.sockets.on('connection', function(sockets){
    sockets.emit('count',{count:data});
})      
}); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...