[英]TypeError: Cannot read property 'id' of undefined in nodejs
I'm struggling to make a function which selects from database based on the id entered in a textbox. 我正在努力制作一个基于在文本框中输入的ID从数据库中进行选择的函数。 I wrote the code, but it shows in console this error and I can't figure why: TypeError: Cannot read property 'id' of undefined
. 我编写了代码,但是它在控制台中显示了此错误,我无法弄清原因: TypeError: Cannot read property 'id' of undefined
。
Code I have so far: 我到目前为止的代码:
Client-side: 客户端:
function select()
{
var id = $('#nr_reg').val();
$.ajax({
type: 'post',
url: '/id',
data : {
id: id
},
succes: function(data){
var id = data.id;
alert(id);
$('#optic').val(id);
},
error: function(err){
console.log(err);
}
});
}
Server-side: 服务器端:
app.post('/id', function(req,res) {
var data = req.body;
var id = data.id;
console.log(id);
var query = "SELECT * FROM Control WHERE id=" +id;
connection.query(query, function(error, result) {
console.log(result);
res.send(result);
});
});
LE: Function select: LE:功能选择:
function select()
{
var id = $('#nr_reg').val();
$.ajax({
type: 'post',
dataType: 'json',
url: '/id',
data : {
id: id
},
success: function(data){
data = JSON.parse(data);
var id = data.id;
alert("merge");
$('#optic').val(id);
},
error: function(err){
console.log(err);
}
});
}
You said your error is on server side? 您说您的错误是在服务器端? Add a body parser to your express app: 将正文解析器添加到您的express应用中:
1st Install body-parser: 1st安装主体解析器:
npm install body-parser -s
The include this in your app: 在您的应用中包括此:
var express = require('express');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post(/*....*/);
Your app.post
must be AFTER app.use
line. 您的app.post
必须在app.use
行之后。
Full example here 完整的例子在这里
BTW this is a duplicate of this 顺便说一句,这是一个重复这个
Make sure you've require
d body-parser
. 确保您require
d body-parser
。 And use bodyParser.urlencoded
. 并使用bodyParser.urlencoded
。
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
This should be before your .post
route definition. 这应该在您的.post
路由定义之前。
EDIT: 编辑:
Before all this, you must do npm install body-parser
:) 在此之前,您必须先npm install body-parser
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.