为什么我的变量没有在node.js中更新?

问题描述 投票:-1回答:1

我已经构建了一个带有node.js的webapp,通过POST请求从SNS主题接收消息,并将它们记录到控制台,然后在网页上显示它们,如果我向主题发布消息,我会在控制台中打印消息,但没有在我的网页上更新?

这是我的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 ##");
});

这是我的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>
javascript node.js embedded-javascript
1个回答
1
投票

因为你的变量是getpost回调函数中的局部变量。如果您希望它们超出这些回调的范围,则需要将它们移动到回调返回时不会消失的范围。

例如,这使得它们成为模块全局变量但是对于每个POST而言,无论它来自哪个,它都会变得奇怪,以改变无关GET的内容(请参阅***注释):

// *** 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});
    }
  });
});

但同样,这可能没有意义。您可能需要某种每用户或每会话存储机制(例如数据库,或内存缓存过期等)。

© www.soinside.com 2019 - 2024. All rights reserved.