gpt4 book ai didi

javascript - 发送表单数据到 Node 服务器

转载 作者:行者123 更新时间:2023-11-30 00:11:27 25 4
gpt4 key购买 nike

我正在尝试将一些表单数据发送到端点。

这是我的客户端代码:

<form name="form" action="http://localhost:8080/geodata" method="post"> 

<label for="minlat"> MinLat: </label>
<input type="text" name="MinLat" value="0"><br>
<label for="maxlat"> MaxLat: </label>
<input type="text" name="MaxLat" value="1"><br>
<label for="minlong"> MinLong: </label>
<input type="text" name="MinLong" value="0"><br>
<label for="maxlong"> MaxLong: </label>
<input type="text" name="MaxLong" value="1"><br>

<button type="submit" class="btn btn-success"> Submit <span class="fa fa-arrow-right"></span></button>

</form>

<script>

$(document).ready(function() {
$("#form")
.submit(function(event) {

var formData = {
'minLat' : $('input[name=MinLat]').val(),
'maxLat' : $('input[name=MaxLat]').val(),
'minLong' : $('input[name=MinLong]').val(),
'maxLong' : $('input[name=MaxLong]').val()
};

$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
dataType: 'json',
processData: false,
type: 'POST',

}).done(function(data) {

console.log(data);
});
event.preventDefault();
});
});
</script>

我在服务器端代码(express.js)上有一个点:

var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");

var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});

app.post("/geodata", function(req, res) {
console.log(req.body);
res.send("hi");
});

我希望将此表单数据发送到端点/geodata,并使用该数据将结果发送回客户端。首先,当我点击提交时,我的终端(即服务器端 request.body)中出现一个空的 {}。我期待此 request.body 中的表单值,但没有收到它们。如何确保发送表单值?

其次,res.send("hi") 将我的初始页面重定向到一个新页面并在那里打印“hi”。由于我进行了 ajax 调用,难道不应该只记录响应并且网页保留在初始页面上吗?

最佳答案

将表单操作更改为“/geodata”(端点)

您也不需要发出 ajax 请求,因为如果按下/单击 tag(),HTML5 表单将自行执行请求。

点击 summit 后,您的页面将变成从“/geodata”路由发回的任何响应req.body 将返回一个表示表单数据的对象

关于javascript - 发送表单数据到 Node 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36323102/

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