Javascript 如何在Ajax中调用Express route?
提交表单时,从Ajax调用Node.js应用程序中的Express route时遇到问题 我的路线如下所示:Javascript 如何在Ajax中调用Express route?,javascript,node.js,ajax,express,Javascript,Node.js,Ajax,Express,提交表单时,从Ajax调用Node.js应用程序中的Express route时遇到问题 我的路线如下所示: router.post("/user", function(req, res) { console.log("FORM DATA: " + JSON.stringify(req.body)); res.send('done!'); }); $("#add-report-form").submit(function(e) { e.preventDefault();
router.post("/user", function(req, res) {
console.log("FORM DATA: " + JSON.stringify(req.body));
res.send('done!');
});
$("#add-report-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
uri: "/user",
contentType: "application/json",
data: JSON.parse(JSON.stringify($("#add-report-form").serializeArray())),
}).done(function(data) {
alert("ajax call done!");
});
});
我的Ajax调用如下所示:
router.post("/user", function(req, res) {
console.log("FORM DATA: " + JSON.stringify(req.body));
res.send('done!');
});
$("#add-report-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
uri: "/user",
contentType: "application/json",
data: JSON.parse(JSON.stringify($("#add-report-form").serializeArray())),
}).done(function(data) {
alert("ajax call done!");
});
});
我的app.jsapp.use(bodyParser.json())中有以下内容:代码>
当我提交表单时,路由中的console.log没有运行,我也不知道为什么,似乎根本没有调用路由。任何帮助都会很好
我的表单如下所示:
<div class="modal-body">
<form id="add-report-form">
<div class="row">
<div class="col">
<label for="report-select">Report</label>
<select class="form-control" id="report-select" name="report">
<option>Select Report</option>
</select>
</div>
</div>
<div class="row modal-row">
<div class="col">
<label for="interval-select">Report Interval</label>
<select class="form-control" id="interval-select" name="interval">
<option>Select Interval</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="add-submit" class="btn btn-primary save-changes">Save changes</button>
</div>
</form>
</div>
问题可能是打字错误。请尝试使用“url”而不是“uri”:
$.ajax({
type: "POST",
url: "/user",
contentType: "application/json",
// data: JSON.parse(JSON.stringify($("#add-report-form").serializeArray())),
data: JSON.stringify({data: "test"}),
}).done(function(data) {
alert("ajax call done!");
});