【问题标题】:Post data on another page in nodejs在nodejs的另一个页面上发布数据
【发布时间】:2017-04-27 13:48:01
【问题描述】:

我是 nodejs 的新手。我正在尝试使用 ejs 引擎制作登录表单。我想要的只是使用发布请求在欢迎屏幕中打印用户名和密码。问题是,如果我使用 POST 操作,它将打印我的数据但不显示欢迎屏幕布局,如果我使用 GET 操作,那么它将显示屏幕布局但没有数据。我已经在 app.js 文件中编写了代码。这是对的吗??我在下面提到了我的 app.js 代码以供参考。提前致谢。

代码:-

app.post('/welcome', function(req, res) {
     res.send('Username is '+req.body.unm+'<br>Password is '+req.body.pwd);
});

【问题讨论】:

  • “但不显示欢迎屏幕布局”,因为您需要将其添加到响应中。 post 和 get 请求完全分开处理
  • @Orangesandlemons 我是 nodejs 的新手。所以你能详细说明一下吗?我没听懂你想说什么。
  • 我想在获取请求路由(我看不到)上,您正在传递页面。在帖子上,您只传递“'用户名是'+req.body.unm+'
    密码是'+req.body.pwd”,这是一个字符串,没有别的。

标签: javascript node.js post ejs


【解决方案1】:

您面临什么问题?返回字符串是否不显示值? 使用模板引擎时,您通常应该使用render 而不是res.send 来发送视图。

查看ejs首页给出的样本。

【讨论】:

  • 我也尝试过渲染,但它给出了类似“无法在视图目录中查找视图“/welcome”之类的错误。所以我认为它可以与 send() 一起使用。但结果是一样的。
【解决方案2】:

在 ejs npm 页面上有一些非常有用的信息:https://www.npmjs.com/package/ejs

我建议您查看express 包,它允许您提供页面,因此您可以从以下内容开始:

app.get('/', function(req, res){
  return res.sendFile(__dirname + '/index.html');
});

这是一个有用的答案,可以帮助你:how to implement login auth in node.js

【讨论】:

  • 但是我要传递的参数呢??
  • 在链接中我添加了“如何在 node.js 中实现登录身份验证”,它准确地描述了这一点。
【解决方案3】:

如果您将 express 与 ejs 一起使用,则需要像这样定义包含视图(.ejs 文件)的文件夹:

var express = require('express')
app.use(express.static(__dirname + '/views')); // set the static files location for the static html

而不是 res.send,回复如下:

app.post('/welcome', function(req, res) {
        res.render('welcome', {username: req.body.unm, password: req.body.pwd});
});

在welcome.ejs 中构建您的html,并为&lt;%= username %&gt; 和&lt;%= password %&gt; 放置占位符

项目库视图目录中的示例welcome.ejs 文件:

<div class="container">
    <p>Welcome<b><%= username %></b></p>
    <p>Your password is <%= password %> </p>
</div>

【讨论】:

    【解决方案4】:

    试试这个..

    这是您的 index.html 文件,您可以在其中填写用户名和密码。我正在调用 display post 操作以在提交时显示您的用户名和密码。

    home.html

    <form action="/display" method="POST">
        <input type="text" placeholder="name" name="name">
        <input type="text" placeholder="password" name="pwd">
        <button type="submit">Submit</button>
    </form>
    

    这是您的 nodejs 代码,它使用 post 请求显示用户名和密码。 express 会通过 get 请求为你的 html 页面提供服务,提交数据时会触发 post 请求。

    const express = require('express')
    const bodyParser = require('body-parser')
    const app = express()
    app.use(bodyParser.urlencoded({
      extended: true
    }))
    
    app.get('/', (req, res) => {
      res.sendFile(__dirname + '/home.html')
    });
    app.post('/display', (req, res) => {
      res.send('Username is ' + req.body.name + '<br>Password is ' + req.body.pwd);
      console.log(req.body)
    });
    
    app.listen(3000, () => {
      console.log('listening on 3000')
    })
    

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多