0

Everyone. I make a small web-site for studying. I have met a problem. actually, It seems very simple error. but In case of me, It is a huge error.

On my system ubuntu, node.js and 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('/');
  });
});

My error message is like title;TypeError: Cannot read property 'name' of undefined.

I know where error is. app.post -> body.name, body.modelnumber, body.series.. I tyed code with reading a book... I can't find why error come..

0

1 Answer 1

1

From the express documentation:

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);
})

Learning from a book is often not enough, you should also read the documentation of libraries/modules you are using.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.