繁体   English   中英

如何从客户端接收node.js中的POST表单数据

[英]How to receive POST form data in node.js from client

大家好,我是Web开发方面的新手,尤其是与node.js一起工作时,我想了解如何接收通过ajax Post从客户端发送的数据。

以下是我编写的用于发布表格数据的脚本

<script type="text/javascript">
function ecoachSignIn(){ 
var user = $('#user').val();
var password = $('#pass').val();

var SignIn ={
    user : $('#user').val();
    pass : $('#pass').val();
};
$.ajax({
    type:'POST',
    url: 'https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user='+username+'&pass='+password,
    data: {
            user : $('#user').val();
            pass : $('#pass').val();
          },
    success: function(creditials){

    }
});
alert("Hello! your username is "+username+" and password is "+password);
}

这是表格本身

<form style="margin-top:25%; margin-left:30%" method="post" action='/'>                                
  <input class="input" type="text" id="user" required="true" name="username" placeholder="Username">               

  <input class="button-1" style="background:#000" onClick="ecoachSignIn()" type="submit" value="Log in">

 <div style="margin-top:10px">  
  <input class="input" type="password" id="pass" name="password" required="true" placeholder="Password">
</div> 
</form>

node.js服务器代码

    router.post('/', function(req, res) {
  var request = require("request"),
      user_name=req.body.username,//this picks the username frome the form directly not from the javascript i created to post the data
      password=req.body.password,//same problem with the username
      url = req.query.url;//trying to get the url in my jQuery at client side but not working
  console.log("Username = "+user_name+", password is "+password);
  request.get(
    {
        url : url
    },
    function (error, response, body) {

        // Do more stuff with 'body' here
       if (!error && response.statusCode == 200) {
        var json_body = JSON.parse(body);
        console.log(json_body); 
        status = json_body.status;
        success = json_body.msg;
        fname = json_body.profile.fname;
    console.log("hi "+fname); // Print the username.
    console.log("status is "+status); // Print the status.
    console.log("success is "+success); // Print the success.
  }
    }
);
  res.end("yes");
});

我的主要问题是如何在node.js后端服务器中处理此问题。希望我的问题很清楚....谢谢

您的服务器端代码:

 user_name=req.body.username,//this picks the username frome the form directly not from the javascript i created to post the data
 password=req.body.password,//same problem with the username

您的客户端代码:

 user : $('#user').val();
 pass : $('#pass').val();

您调用字段userpass客户端,但pass服务器上的usernamepassword 您必须在两个地方使用相同的名称。

当您正常使用表单时,它会起作用,因为名称属性与您在服务器上使用的名称匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM