简体   繁体   English

NodeJS,Express,Jade POST JSON到数据库

[英]NodeJS, Express, Jade POST JSON into DB

I encountered a frustrating problem while following a tutorial based on NodeJS, Express, Jade and MongoDB. 在遵循基于NodeJS,Express,Jade和MongoDB的教程时,我遇到了一个令人沮丧的问题。 This issue has been discussed in other threads on this forum but even following the suggestions already posted, i am unable to get the POST command to work. 在此论坛上的其他线程中已经讨论了此问题,但是即使遵循已经发布的建议,我也无法使POST命令起作用。

Don't think about the Jade indentation, it might be a little wrong in the copy+paste but correct in the actual code. 不用考虑Jade缩进,在复制粘贴中可能有点错误,但是在实际代码中是正确的。

When i POST from my input.js page the site throws me a 404 error. 当我POST从我input.js网页的网站抛出了我一个404错误。 I know it is not a DB problem because i can output data on other pages just fine. 我知道这不是数据库问题,因为我可以在其他页面上输出数据。

My Jade template for input.js. 我的Jade用于input.js的模板。

    extends head
    block content

    div(id="input_page_wrapper")
        div(id="input")
            form(id="input_form", name="addEntry", method="post" action="/addEntry")

            div(class="label_box")
                label(for="restname") Restaurant Name: 
            input(type="text", placeholder="Example: Soul Kitchen", name="restname")

            div(class="label_box")
                label(for="restdesc") Restaurant Description: 
            input(type="text", placeholder="Write a short description.", name="restdesc")

            div(class="label_box")
                label(for="restdesc") Restaurant Address: 
            input(type="text", placeholder="Example: Fleminginkatu 26", name="restadd")

            button(id="submit", name="submit", type="submit") submit

My input.js Route 我的input.js路线

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

    /* GET Input page. */
    router.get('/', function(req, res) {
    res.render('input', { title: 'Input to Database' });
    });

    /* POST to Add User Entry */
    router.post("/addEntry", function(req, res) {

    // Set our internal DB variable
    var db = req.db;

    // Get our form values. These rely on the "name" attributes
    var restName = req.body.restname;
    var restDesc = req.body.restdesc;
    var restAdd = req.body.restadd;
    console.log("post received: %s %s", restName, restDesc, restAdd);

    // Set our collection
    var collection = db.get('restaurants');

    // Submit to the DB
    collection.insert({
        "name" : restName,
        "desc" : restDesc,
        "address" : restAdd
    }, function (err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem adding the information to the database.");
        }
        else {
            // And forward to success page
            res.redirect("/input");
        }
      });
    });

    module.exports = router;

My App.js file 我的App.js文件

    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var mongo = require('mongodb');
    var monk = require('monk');
    var db = monk('localhost:27017/nodetest1');

    var routes = require('./routes/index');
    var input = require('./routes/input');

    var app = express();

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

    // uncomment after placing your favicon in /public
    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

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

    app.use('/', routes);
    app.use('/input', input);

    /// catch 404 and forwarding to error handler
    app.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

   /// error handlers

   // development error handler
   // will print stacktrace
   if (app.get('env') === 'development') {
       app.use(function(err, req, res, next) {
       res.status(err.status || 500);
       res.render('error', {
           message: err.message,
           error: err
       });
     });
    }

  // production error handler
  // no stacktraces leaked to user
  app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
         message: err.message,
         error: {}
      });
  });

    module.exports = app;

Entire source code is also viewable in GitHub. 整个源代码也可以在GitHub中查看。 https://github.com/ValterAndersson/DinnerApp https://github.com/ValterAndersson/DinnerApp

I think you need indent your tags in form, try this, and miss a ',' in form tag (after method="post"): 我认为您需要在表单中缩进标签,然后尝试这样做,并在表单标签中遗漏“,”(在method =“ post”之后):

 extends head block content div(id="input_page_wrapper") div(id="input") form(id="input_form", name="addEntry", method="post", action="/input/addEntry") div(class="label_box") label(for="restname") Restaurant Name: input(type="text", placeholder="Example: Soul Kitchen", name="restname") div(class="label_box") label(for="restdesc") Restaurant Description: input(type="text", placeholder="Write a short description.", name="restdesc") div(class="label_box") label(for="restdesc") Restaurant Address: input(type="text", placeholder="Example: Fleminginkatu 26", name="restadd") button(id="submit", name="submit", type="submit") submit 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM