【发布时间】:2019-02-05 20:11:00
【问题描述】:
我正在尝试从站点向服务器发送一个包含用户输入数据的发布请求。我收到 TypeError: Cannot read property 'vehicle' of undefined as a response here。
HTML 和脚本数据:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Car Finder</title>
<link rel="stylesheet" href="style.css">
<center><h1>Craigslist Vehicle Finder</h1></center>
</head>
<body>
<form class="form">
<input type="text" name="vehicle" value="" id="vehicle">
<label for="vehicle">Vehicle</label>
</form>
<form class="form">
<input type="text" name="miles" value="" id="miles">
<label for="miles">Miles</label>
</form>
<label class="container">
<input type="checkbox" id="checkbox">
<span class="checkmark"></span>
<label for="checkbox">Manual</label>
</label>
<select id="select" class="City">
<option value="null">Select Location</option>
</select>
</div>
<form class="submit Search">
<input type="submit" value="Search Craigslist"><br/>
</form>
<script>
var select = document.getElementById("select"),
arr = ["atlanta","austin","boston","chicago","dallas","denver","detroit","houston","lasvegas","losangeles","miami","minneapolis","newyork","newhaven","orangecounty","philadelphia","phoenix","portland","raleigh","sacramento","san diego","seattle","sfbay","washingtondc"];
for(var i = 0; i < arr.length; i++) {
var option = document.createElement ("OPTION"),
txt = document.createTextNode(arr[i]);
option.appendChild(txt);
select.insertBefore(option, select.lastChild);
}
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$.post('http://localhost:3000', { vehicle: 'input#vehicle', miles: 'input#miles', location: 'select' }, function (err, result) {
if (err) {
console.log(err);
} else {
return data;
}
});
</script>
</body>
</html>
服务器端接收POST数据的方法:
app.post('/', (req, res, err) => {
if (req.method == 'POST') {
console.log(req.body.vehicle)
console.log(req.body.miles)
console.log(req.body.location)
}
})
顺便说一句,使用快递服务器
【问题讨论】:
-
尝试登录
req.body看看它有什么?以下也是无效的。$.post('http://localhost:3000', { vehicle: 'input#vehicle', miles: 'input#miles', location: 'select' }, function (err, result) {您实际上是在将这些字符串作为这些键的值发送,而不是在页面上查找元素。 -
试试:
$.post('http://localhost:3000', { vehicle: $('input#vehicle').val(), miles: $('input#miles').val(), location: $('select').val() }, function (err, result) { -
return data;... 而data来自哪里? --- 并返回到哪里? -
当我使用这两个建议记录正文时,我收到“未定义”作为响应
-
如果你只记录
req呢?
标签: javascript jquery html node.js express