【问题标题】:nodejs app receive data from post and render to htmlnodejs 应用程序从 post 接收数据并渲染到 html
【发布时间】:2017-06-08 17:52:54
【问题描述】:

我刚开始使用 node.js,但我不太明白一些事情。所以请不要吝啬。我尝试在网上搜索,但没有太多结果。

我希望一个网页继续等待帖子,然后呈现收到的数据。 到目前为止,我有以下 app.js

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing 
    application/x-www-form-urlencoded

    app.set('view engine', 'pug');

    app.get('/', function (req, res) {
     res.render('index', {title: 'GET test',message : 'GET test'});
    });

    var data = "";

    app.post("/",function(req, res) {

    console.log(req.method);
    console.log(req.headers);
    console.log(req.url);
    data=req.body
    console.log(data);
    res.render('index', {title: 'POST test',message : 'POST test'});

    });



    app.listen(8081, function () {
      console.log('Example app listening on port 8081!');
    });

views/index.pug我有

    html
     head
      title = title
     body
      h1 = message

每当我触发curl --data "field=value" http://127.0.0.1:8081/ 我可以看到终端内收到的帖子,但我不明白如何在页面中呈现这些数据。

【问题讨论】:

    标签: javascript node.js curl


    【解决方案1】:

    您需要在 POST 执行时发送数据响应,例如:

     res.status(201).send("POST executed successufully");
    

    然后,在您的 Javascript 调用中;您可以捕获 POST 响应并使用以下内容呈现您想要的内容:

    $.ajax({
        success: function(data, textStatus, xhr) {
            console.log(xhr.status);
        },
        complete: function(xhr, textStatus) {
            console.log(xhr.status);
        } 
    });
    

    【讨论】:

    • 谢谢。我应该把 ajax 代码放在哪里?
    • Ajax 代码在 html/JS 部分(前端),消耗旅游 web 服务
    【解决方案2】:

    看起来好像您没有将数据传递给 res.render 方法。

    console.log(data);
    res.render('index', {title: 'POST test',message : 'POST test', postData: data});
    
    html
     head
      title = title
     body
      h1 = message
      span = postData.field
    

    ^ 这是假设“字段”存在于帖子正文中,实际上您希望以更动态的方式执行此操作并确保它存在。

    【讨论】:

    • 谢谢。我的问题是页面没有改变。我希望在收到帖子时使用“发布测试”呈现页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多