首页 > 解决方案 > 为什么 req.body 在我的显示和编辑路线中未定义,而不是我的创建路线?

问题描述

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

我试过用谷歌搜索解决方案,在 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)

标签: javascriptexpressbody-parser

解决方案


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

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

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

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

以上几行需要修改

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


推荐阅读