开发者问题收集

TypeError:无法读取未定义的mysql查询的属性“名称”

2015-02-04
904

各位。 我制作了一个小型网站用于学习。我遇到了一个问题。实际上,这似乎是非常简单的错误。但就我而言,这是一个巨大的错误。

在我的系统 ubuntu、node.js 和 mysql 上。

var fs = require('fs');
var ejs = require('ejs');
var http = require('http');
var mysql = require('mysql');
var express = require('express');

var client = mysql.createConnection({
  user: 'root',
  password: 'password',
  database: 'Company'
});

var app = express();

http.createServer(app).listen(8080, function(){
  console.log('Server running at http://127.0.0.1:8080');
});

app.get('/', function(request, response) {
  fs.readFile('list.html', 'utf8', function(error, data) {
    client.query('SELECT * FROM products', function (error, results) {
       response.send(ejs.render(data, {
        data: results
      }));
    });
  });
});


app.get('/delete/:id', function(request, response) { 
  client.query('DELETE FROM products WHERE id=?', [request.param('id')], function() {
    response.redirect('/');
  });
});

app.get('/insert', function(request, response) { 
  fs.readFile('insert.html', 'utf8', function (error, data) {
  response.send(data);
  });
}); 

app.post('/insert', function(request, response) {
  var body = request.body;

  client.query('INSERT INTO products (name, modelnumber, series) VALUES (?, ?, ?)', [
       body.name, body.modelnumber, body.series 
  ],function() {
    response.redirect('/');
  });
});

我的错误消息类似于 title;TypeError:无法读取未定义的属性“name”。

我知道错误在哪里。app.post -> body.name、body.modelnumber、body.series.. 我把代码和读书结合起来... 我找不到错误出现的原因..

1个回答

摘自 express 文档 :

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined , and is populated when you use body-parsing middleware such as body-parser and multer .

This example shows how to use body-parsing middleware to populate req.body.

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); 

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

app.post('/', function (req, res) {
  console.log(req.body);
  res.json(req.body);
})

仅从书本上学习往往是不够的,您还应该阅读您正在使用的库/模块的文档。

Felix Kling
2015-02-04