我正在尝试通过ajax将表单数据发送到nodejs服务器。
这是我的代码看起来像(EDITED):
<div id="inputid" style="width: 400px; height:400px">
<p> Please enter the respective values in each field and hit Submit </p>
<form id="sendCoordinates" action="http://localhost:8080/geodata" method="post">
MinLat: <input type="text" name="MinLat" id="minlat"><br>
MaxLat: <input type="text" name="MaxLat" id="maxlat"><br>
MinLong: <input type="text" name="MinLong" id="minlong"><br>
MinLong: <input type="text" name="MaxLong" id="maxlong"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$(document).ready(function() {
$(sendCoordinates)
.on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray();
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
console.log(formData);
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
console.log(result);
}
});
});
});
</script>
我的服务器端代码如下所示:
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);
});
// for debugging purposes, just logging the request to check
// if request received
app.post("/geodata", function(req, res) {
console.log(req.body);
});
我正在尝试这个,但我无法成功发送表单,并且在点击提交时,没有任何反应。我无法在客户端记录formData
,也无法在服务器端的端点上记录输出。
有人可以指出我可能做错了吗?当我点击提交时,我得到的只是一个空的{}。我的"action"
中的form
标记是否指向发布到端点/geodata
的正确网址?