【发布时间】:2017-03-05 00:18:21
【问题描述】:
我正在尝试使用 AJAX 将简单的表单数据发送到节点/快递服务器。提交时,我被带到无法发布 / 页面,虽然我能够 console.log 一个请求,但它不包含表单中的数据。我错过了什么?
表格
<form method="POST" class="form-group">
<label for="sentenceCount">Sentences</label>
<input type="number" placeholder="10" name="sentence count" id="sentenceCount" class="form-control parameters">
<button type="submit" id="submit" class="btn btn-primary mt-1">Submit</button>
</form>
AJAX 请求 $('button').on('click', function(data) {
$.ajax({
data: data,
url: '/data',
type: "POST"
})
}
)
服务器.js
var express = require('express');
var app = express();
app.listen(8000)
app.get('/', function (req, res) {
res.sendFile('/Index.html', {
root: __dirname
})
});
app.post('/data', function (req, res) {
console.log(req)
})
更新:
我摆弄了一下,能够访问 body 属性,但 body 是空的,无法获得我需要的输入值。
AJAX:
$('button').on('click', function(data) {
var formData = $('input').val();
console.log(formData)
$.ajax({
data: formData,
url: '/data',
type: "post"
})
}
)
服务器:
app.get('/', function (req, res) {
res.sendFile('/Index.html', {
root: __dirname
})
});
app.use(bodyParser.json())
app.post('/data', function(req, res) {
console.log(req.body)
});
【问题讨论】:
标签: javascript ajax node.js express