I have built a webapp with node.js to receive messages from an SNS topic via POST request and log them to the console then display them on the webpage, if I publish a message to my topic I get the message printed in the console but nothing updates on my webpage?
This is my code for app.js
const express = require("express");
const request = require('request')
const bodyParser = require('body-parser')
const app = express();
app.use(express.static('public'));
app.set("view engine", "ejs")
app.get('/', function (req, res) {
let subject = "Your Subject Will Appear Here";
let message = "Your Message Will Appear Here";
res.render("index", {subject:subject, message:message});
})
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post('/', (req, res) => {
let body = ''
req.on('data', (chunk) => {
body += chunk.toString()
})
req.on('end', () => {
let payload = JSON.parse(body)
if (payload.Type === 'Notification') {
console.log(payload.Message);
let subject = payload.Subject;
let message = payload.Message;
res.render("index", {subject:subject, message:message});
}
});
});
app.listen(80, process.env.IP, function(request, response){
console.log("## SERVER STARTED ##");
});
This is my code for index.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<fieldset>
<% if(subject !== null){ %>
<p>SNS Subject: <%= subject %></p>
<% } %>
<% if(message !== null){ %>
<p>SNS Message: <%= message %></p>
<% } %>
</fieldset>
</div>
</body>
</html>
Because your variables are local variables within the get
and post
callback functions. If you want them to persist outside the scope of those callbacks, you need to move them to a scope that won't go away when the callback returns.
For instance, this makes them module globals BUT it seems like it would be odd for every POST, regardless of who it came from, to change the content of unrelated GETs (see ***
comments):
// *** Declared at module scope
let subject = "Your Subject Will Appear Here";
let message = "Your Message Will Appear Here";
app.get('/', function (req, res) {
// *** Not declared here
res.render("index", {subject:subject, message:message});
})
// ...
app.post('/', (req, res) => {
let body = ''
req.on('data', (chunk) => {
body += chunk.toString()
})
req.on('end', () => {
let payload = JSON.parse(body)
if (payload.Type === 'Notification') {
console.log(payload.Message);
subject = payload.Subject; // <======= *** no `let`, we're not declaring here
message = payload.Message; // <======= *** same
res.render("index", {subject:subject, message:message});
}
});
});
But again, that probably wouldn't make sense. You'll probably need some kind of per-user or per-session storage mechanism (such as a database, or expiring in-memory cache, etc.).