ExpressJS邮政路线无效并返回错误

时间:2017-11-14 14:27:16

标签: node.js express post mean-stack

我正在开发一个Mean堆栈应用程序,我已经定义了一个expressjs后端post路由以在服务器上存储一些数据,但是它不起作用并返回一条错误消息,该消息是为处理错误而提供的“表单api中发生了错误” 。 enter image description here

router.post('/userform', function (req, res, next) {
    var form = new Form({
        controlType: req.body.controlType,
        label: req.body.label,
        required:req.body.required ,        
        placeholder: req.body.placeholder,
        options: req.body.options
    });
    form.save(function(err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred in form api',
                error: err
            });
        }
        res.status(201).json({
            message: 'Form created',
            obj: result
        });
    });
});

我正在使用的mongoose架构:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');

var formSchema = new Schema({    
    controlType: {type: String, required: true},   
    label: {type: String, required: true},
    required: {type: Boolean}, 
    placeholder: {type: String},   
    options: [String],    //to store options for select or radio input
} ,  {collection: 'inputForm'});

formSchema.plugin(mongooseUniqueValidator);

module.exports = mongoose.model('Form', formSchema);

这是app.js文件:

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

var mongoose = require('mongoose');
// Get our API routes
const api = require('./routes/api');
const formApi = require('./routes/form');


const app = express();
mongoose.connect('localhost:27017/test-mean');

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

//to avoid cross origin requests errors
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();
});


// Set our api routes
app.use('/api', api);
app.use('/form', formApi);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

请帮忙。感谢

1 个答案:

答案 0 :(得分:0)

  

在所有路由器上添加您的身体解析器代码

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

var mongoose = require('mongoose');

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Get our API routes
const api = require('./routes/api');
const formApi = require('./routes/form');


const app = express();
mongoose.connect('localhost:27017/test-mean');


// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

//to avoid cross origin requests errors
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();
});


// Set our api routes
app.use('/api', api);
app.use('/form', formApi);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));