发送响应到浏览器

时间:2017-09-26 08:00:16

标签: javascript node.js

如何在浏览器页面上显示表单的输出,而不仅仅是在控制台上?

这是我的代码:

var express = require('express')
var bodyParser = require("body-parser");
var app = express()
var http = require('http');

app.get('/', function(request, response, next) {
    response.send("My Server");
});

app.use(express.static('public'))


app.use(bodyParser.urlencoded({ extended: false }));


app.post('/users', function (req, res, next) {
    let username = req.body.name;
    let password = req.body.password;

    console.log("Just received POST data for users endpoint!");
    console.log(`Data includes: ${username}, ${password}`);
});

1 个答案:

答案 0 :(得分:0)

假设您已在server-sise上配置了此路由:

app.post('/users', function (req, res, next) {
    let _username = req.body.name;
    let _password = req.body.password;
    res.send({username: _username, pwd: _password});
});

而且,客户端,您正在使用JQuery,并且您将使用此HTML表单向服务器发出异步请求:

<form name="module">
    <p>Username</p>
    <p><input type="text" name="username" id="username"></p>
    <p>Password</p>
    <p><input type="text" name="password" id="password"></p>
    <input type="button" id="submit" value="Send">
</form>

<div id="result"></div>

您可以发出POST请求并以这种方式解析响应数据:

<script type="text/javascript">
$(document).ready(function() {
  $("#submit").click(function(){
    var _username= $("#username").val();
    var _password= $("#password").val();
    $.ajax({
      type: "POST",
      url: "<YOUR_NODEJS_SERVER_URL>",
      data: '{"username":_username, "password": _password}',
      contentType: "application/json",
      dataType: 'json',
      success: function(response)
      {
        $("#result").html(response.username + "<br/>" + response.pwd);
      },
      error: function(error)
      {
        alert(error);
      }
    });
  });
});
</script>