Express.js POST请求未定义

时间:2019-10-14 18:07:07

标签: node.js express sequelize.js

我需要向服务器发出POST请求,以通过Express和Sequelize将一些数据放入数据库中

var express = require('express'),
    http = require('http'),
    path = require('path'),
    Sequelize = require('sequelize'),
    bodyParser = require('body-parser'),
    _ = require('lodash');

sequelize = new Sequelize('sqlite://' + path.join(__dirname, 'invoices.sqlite'), {
  dialect: 'sqlite',
  storage: path.join(__dirname, 'invoices.sqlite')
});

Invoice = sequelize.define('invoices', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  customer_id: {
    type: Sequelize.INTEGER
  },
  discount: {
    type: Sequelize.DECIMAL
  },
  total: {
    type: Sequelize.DECIMAL
  }
});

var app = module.exports = express();
app.set('port', process.env.PORT || 8000);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.route('/api/invoices')
  .post(function(req, res) {
    let invoice = Invoice.build(_.pick(req.body, ['customer_id', 'discount', 'total']));
    invoice.save().then(function(invoice){
      res.json(invoice);
    });
  });

但是,在通过POST请求进行抓取时,未定义作为要求。提取请求正文不为空,我已经检查了它。

1 个答案:

答案 0 :(得分:0)

    app.post('/api/invoices',
      (function(req, res) {
        let invoice = Invoice.build(_.pick(req.body, ['customer_id', 'discount', 'total']));
        invoice.save().then(function(invoice){
          res.json(invoice);
        });
      });

不使用路线。...