req.body.variable名称显示节点js中的未定义值

时间:2018-06-18 16:34:25

标签: javascript node.js express

我是Node js的新手,并尝试创建一个博客系统。当我试图在categories.js文件中控制发布的值时,我得到了值" undefined"。我使用post.js添加新帖子和category.js来添加新类别。

这是我的app.js文件。

var createError = require('http-errors');
var express = require('express');
var expressValidator = require('express-validator');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var multer = require('multer');
var upload = multer({dest: './public/images/uploads'});
var flash = require('connect-flash');
var logger = require('morgan');
var mongodb = require('mongodb');
var db = require('monk')('localhost/nodeblog');

var indexRouter = require('./routes/index');
var posts = require('./routes/posts');
var categ = require('./routes/categories');

var app = express();

app.locals.moment = require('moment');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Session
app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true
}));

// Validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
    var namespace = param.split('.')
    , root = namespace.shift()
    , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }

    return {
      param: formParam,
      msg: msg,
      value: value
    };
  }
}));

// Connect Flash
app.use(require('connect-flash')());
app.use(flash());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Make our db accessible to our router
app.use(function(req, res, next) {
  req.db = db;
  next();
});

app.use('/', indexRouter);
app.use('/posts', posts);
app.use('/categories', categ);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

这是我的post.js文件

var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var multer = require('multer');
var upload = multer({dest: './public/images/uploads'});
var db = require('monk')('localhost/nodeblog');

router.get('/add', function(req, res, next) {
    var categories = db.get('categories');
    categories.find({}, {}, function(err, categories) {
        res.render('addpost', {
            "title" : "Add Post",
            "categories": categories
        });
    });
});

router.post('/add', upload.single('profileimage'), function(req, res, next) {

    // Getting Form Values 

    var title       = req.body.title;
    console.log(title);
    var category    = req.body.category;
    var body        = req.body.body;
    var author      = req.body.author;
    var date        = new Date();

    if(req.file) {
        var profileimage = req.file.filename;
    } else {
        var profileimage = 'noimage.png';
    }

    // Form Validation
    req.checkBody('title', 'Title Field is required').notEmpty();
    req.checkBody('body', 'Body field is required').notEmpty();

    // Check for Errors
    var errors = req.validationErrors();

    if(errors) {

        res.render('addpost', {
            "errors": errors,
            "title": title,
            "body": body
        });
    } else {
        var posts = db.get('posts');

        // Submitting values to DB
        posts.insert({
            "title": title,
            "body": body,
            "category": category,
            "date": date,
            "author": author,
            "profileimage": profileimage
        }, function(err, post) {
            if(err) {
                res.send("There is an issue in submitting the post");
            } else {
                req.flash('success','Post Submitted Successfully');
                res.location('/');
                res.redirect('/');
            }
        });
    }
});



module.exports = router;

这是我的分类文件。

var express = require('express');
var router = express.Router();

router.get('/add', function(req, res, next) {
    res.render('addcategory', {
        "title" : "Add Category"
    });
});

router.post('/add', function(req, res, next) {

    // Getting Form Values 
    var title       = req.body.title;
    //console.log(req.body);
    console.log(title);
});



module.exports = router;

这是addcategory jade文件。

extends layout

block content
    h1=title
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/categories/add', enctype='multipart/form-data')
        .form-group
            label Title:
            input.form-control(name='title',type='text')
        input.btn.btn-default(name='submit',type='submit',value='Save')

这是post jade文件。

扩展布局

block content
    h1=title
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/posts/add', enctype='multipart/form-data')
        .form-group
            label Title:
            input.form-control(name='title', type='text')
        .form-group
            label Category
            select.form-control(name='category')
                each category, i in categories
                    option(value= '#{category.title}') #{category.title}
        .form-group
            label Body
            textarea.form-control(name='body', id='body')        
        .form-group
            label Main Image
            input.form-control(name='profileimage', type='file')
        .form-group
            label Author
            select.form-control(name='author')
                option(value='Deepesh') Deepesh
                option(value='Sudha') Sudha
        input.btn.btn-default(name='submit', type='submit', value='Save')
        script(src='/ckeditor/ckeditor.js')
        script
            | CKEDITOR.replace('body');

我在post.js中获得req.body值。但是当我试图在categories.js中获得相同时,我得到的值是未定义的。我需要在类别文件中获取title的值,其中相同的值应该在post文件中。

你们能找到我同样的解决方案吗?我尝试过,但没有得到适当的解决方案。

1 个答案:

答案 0 :(得分:0)

路由是指确定应用程序如何响应客户对特定端点的请求。您为同一端点创建了2个路由器。

router.post('/add', function(req, res, next) {} //in categories.js and post js

一旦您请求数据,数据将到达指定的地址,路由器将处理并处理它。因此,您将收到对post.js的请求,express处理该请求,然后对其进行响应。这样该请求将被终止。

但是在category.js中,您正在等待已经消失的相同请求。如果您想测试它,请在post.js中注释掉router.post,然后您会看到express将处理category.js中的请求。