gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:47:37 26 4
gpt4 key购买 nike

大家好,我是 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,但在服务器上调用usernamepassword。您必须在两个地方使用相同的名称。

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

关于javascript - 如何在node.js中从客户端接收POST表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28090038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com