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

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

本文关键字:中的 js POST 表单 数据 节点 客户 客户端 端接      更新时间:2023-09-26

大家好,我是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>

节点.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,但在服务器上调用usernamepassword字段。您必须在两个地方使用相同的名称。

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