Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript nodejs应用程序从post接收数据并渲染为html_Javascript_Node.js_Curl - Fatal编程技术网

Javascript nodejs应用程序从post接收数据并渲染为html

Javascript nodejs应用程序从post接收数据并渲染为html,javascript,node.js,curl,Javascript,Node.js,Curl,我刚刚开始使用node.js,我不太了解一些事情。所以请不要吝啬。我试着在网上搜索,结果却不多 我想要一个网页继续等待帖子,然后呈现收到的数据。 到目前为止,我有以下app.js var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json()); // for parsing appli

我刚刚开始使用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!');
    });
视图/index.pug中
我有

    html
     head
      title = title
     body
      h1 = message
每当我触发curl--data“field=value”http://127.0.0.1:8081/
我可以看到终端内部接收到的post,但我无法理解如何在页面中呈现这些数据。

您需要在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);
    } 
});

看起来好像没有将数据传递到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

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

谢谢。我应该把ajax代码放在哪里?ajax代码位于html/JS部分(前端),它使用tour Web服务谢谢。我的问题是页面没有改变。我想有一些东西,使页面在收到帖子时显示“Post test”。