为什么在我的显示和编辑路线中未定义req.body而不在我的创建路线中未定义?

时间:2019-05-12 19:15:51

标签: javascript express body-parser

我重构了代码,并将一些东西分解成模型以简化我的app.js文件。这样做之后,我开始收到错误,指出req.body对象中的项目未定义。对于我的一生,我无法弄清楚原因。

我尝试使用Google搜索解决方案,在Stackoverflow上进行搜索,并阅读我的代码约5,000次以发现问题,但无济于事。

var express             = require('express'),
    app                 = express(), 
    bodyParser          = require('body-parser'),
    methodOverride      = require('method-override'),
    expressSanitizer    = require("express-sanitizer"),
    mongoose            = require('mongoose'),
    Job                 = require("./models/job"),
    Worker              = require("./models/worker"),
    Boss                = require("./models/boss");

mongoose.connect("mongodb://localhost/tiny_gig", { useNewUrlParser: true });
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(expressSanitizer());
app.use(methodOverride("_method"));



// CREATE ROUTE
app.post("/jobs", function(req,res){
   req.body.job.jobInfo = req.sanitize(req.body.job.jobInfo); // <--- This works just fine.
   // Create job
   Job.create(req.body.job, function(err, newlyCreated){
        if(err){
          res.render("new");
        } else {
          res.redirect("/jobs");
        }       
   });
});


// SHOW ROUTE
app.get("/jobs/:id", function(req, res) {
   // Find the job with the specific ID
   console.log(req.body);
   Job.findById(req.params.id, function(err, foundJob){
      if(err){
        res.redirect("/jobs");
      } else {
        res.render("show", {job: foundJob});
      }
   });
});


// EDIT ROUTE
app.get("/jobs/:id/edit", function(req, res) {
    req.body.job.jobInfo = req.sanitize(req.body.job.jobInfo); // <--- If I comment this line out, everything works...
    Job.findById(req.params.id, function(err, foundJob){
        if(err){
            res.redirect("/jobs");
        } else {
            res.render("edit", {job: foundJob});
        }
    });
});

以下是EJS模板:

// EDIT TEMPLATE
<% include partials/header %>
<div class="ui main text container segment">
    <div class="ui huge header">Edit "<%= job.title %>" </div>
    <form class="ui form" action="/jobs/<%= job._id %>?_method=PUT" method="POST"> 
        <div class="field">
            <input type="text" name="job[title]" value="<%= job.title %>">
        </div>
        <div class="field">
            <input type="text" name="job[preview]" value="<%= job.preview %>">
        </div>
        <div class="field">
            <textarea required name="job[jobInfo]"><%= job.jobInfo %></textarea>
        </div>
        <div class="field">
            <input class="ui teal basic button" type="submit">
        </div>
    </form>
</div>
// SHOW TEMPLATE
<% include partials/header %>

<div class="ui main text container ">
    <div class="ui huge header"><%= job.title %></div>

    <div class="ui top attached segment">
        <div class="item">
            <div class="description">
                <p><%=job.jobInfo%></p>
                <div class="content">
                    <span><small>Created on:  <em><%= job.created.toDateString() %></em></small></span>
                </div>
                <a class="ui teal basic button" href="/jobs/<%= job._id %>/edit">Edit</a>
                <form id="delete" action="/jobs/<%= job._id %>?_method=DELETE" method="POST">
                    <button class="ui red basic button">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>
\\ JOBS MODEL
`code`
var mongoose = require("mongoose");


// JOB SCHEMA SETUP
var jobSchema = new mongoose.Schema({
    title: String, 
    preview: String,
    jobInfo: String,
    created: {type: Date, default: Date.now}
});

module.exports = mongoose.model("Job", jobSchema);

我得到的错误

TypeError: Cannot read property 'jobInfo' of undefined
    at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/app.js:71:53
    at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
    at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:281:22
    at param (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:354:14)
    at param (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:365:14)
    at Function.process_params (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:410:3)
    at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:275:10)
    at methodOverride (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/method-override/index.js:65:14)
    at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:317:13)
    at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:335:12)
    at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:275:10)

1 个答案:

答案 0 :(得分:2)

req.body仅可用于发布请求,而不能用于获取请求

您的查看和编辑URL被注册为获取请求。您可以使用req.query来访问网址参数

app.get("/jobs/:id", function(req, res) {

app.get("/jobs/:id/edit", function(req, res) {

以上行需要修改

使用app.post()或将req.body更改为req.query以访问URL参数。