【问题标题】:Cannot read property 'destroy' of null无法读取 null 的属性“销毁”
【发布时间】:2020-09-18 20:46:20
【问题描述】:

我想在我的 NODE JS 应用程序中删除一个产品 这是我的代码:-

exports.postEditProduct = (req, res, next) => { // working correctly
  const prodId = req.body.productId;
  const updatedTitle = req.body.title;
  const updatedPrice = req.body.price;
  const updatedImageUrl = req.body.imageUrl;
  const updatedDesc = req.body.description;
  Product.findByPk(prodId)
    .then(product => {
      product.title = updatedTitle,
      product.price = updatedPrice,
      product.description = updatedDesc,
      product.imageUrl = updatedImageUrl
      return product.save(); // method provided by sequelize
    })
    .then(result => {
      console.log('UPDATED PRODUCT');
    })
    .catch(err => console.log(err));
  res.redirect('/admin/products');
}


exports.postDeleteProduct = (req, res, next) => {
  const prodId = req.body.productId; // prodId is NULL; why??
  console.log('ID = ',prodId);
  Product.findByPk(prodId)
    .then(product => {
      return product.destroy();
    })
    .then(result => {
      console.log('DELETED PRODUCT')
      res.redirect('/admin/products');
    })
    .catch(err => console.log(err));
}

这是我的 product.ejs 文件:-

<%- include('../includes/head.ejs') %>
    <link rel="stylesheet" href="/css/product.css">
    </head>

    <body>
        <%- include('../includes/navigation.ejs') %>

            <main>
                <% if (prods.length > 0) { %>
                    <div class="grid">
                        <% for (let product of prods) { %>
                            <article class="card product-item">
                                <header class="card__header">
                                    <h1 class="product__title">
                                        <%= product.title %>
                                    </h1>
                                </header>
                                <div class="card__image">
                                    <img src="<%= product.imageUrl %>" alt="<%= product.title %>">
                                </div>
                                <div class="card__content">
                                    <h2 class="product__price">$
                                        <%= product.price %>
                                    </h2>
                                    <p class="product__description">
                                        <%= product.description %>
                                    </p>
                                </div>
                                <div class="card__actions">
                                    <a href="/admin/edit-product/<%= product.id %>?edit=true" class="btn">Edit</a>
                                    <form action="/admin/delete-product" method="POST">
                                        <input type="hidden" value="<% product.id %>" name="productId">
                                        <button class="btn" type="submit">Delete</button>
                                    </form>

                                </div>
                            </article>
                            <% } %>
                    </div>
                    <% } else { %>
                        <h1>No Products Found!</h1>
                        <% } %>
            </main>
            <%- include('../includes/end.ejs') %>

这是我在路由文件夹中调用 postDeleteProduct 函数的 admin.js 文件。

const express = require('express');
const path = require('path');

const router = express.Router();

//const rootDir = require('../util/path');
const adminController = require('../controllers/admin');


// /admin/add-product  => GET
router.get('/add-product',adminController.getAddProduct); // don't add parenthesis

// /admin/add-product  => GET
router.get('/products',adminController.getProducts); // don't add parenthesis

// /amin/add-product  => POST
router.post('/add-product', adminController.postAddProduct);

router.get('/edit-product/:productId', adminController.getEditProduct);

router.post('/edit-product',adminController.postEditProduct);

router.post('/delete-product',adminController.postDeleteProduct);

// module.exports = router;

module.exports = router;  // exports.router can be used if we are exporting more than one...
//exports.products = products;  

这也是我的 app.js 文件:-

//const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
//const expressHbs = require('express-handlebars');

const app = express();

// app.engine('hbs', expressHbs({layoutsDir: 'views/layouts/',defaultLayout: 'main-layout' ,extname: 'hbs'}))
//app.set('view engine', 'pug');
//app.set('view engine', 'hbs')
app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
const errorController = require('./controllers/404');
const sequelize = require('./util/database');
const Product = require('./models/product');



app.use(bodyParser.urlencoded({extended: false}));
// returns middleware that only parses urlencoded bodies and only look at
// requests where Content-Type header matches the type option.
// a new body object containing the parsed data is populated on the request object
// after the middleware(req.body). This object will contain key-value pairs, where
// value can be string or array(when extended is false), or any type
// (when extended is true);

app.use(express.static(path.join(__dirname,'public')))

app.use('/admin',adminRoutes);
app.use(shopRoutes);

app.use(errorController.error);

//const server = http.createServer(app);

sequelize.sync().then(result => {
  //console.log(result);
  app.listen(3000);
})
.catch(err => {
  console.log(err);
})

我收到此错误:-

Cannot read property 'destroy' of null
    at /home/pratik/Desktop/NODE JS/Express/controllers/admin.js:93:22

有人可以帮我解决这个问题吗? req.body.prodId 应该给我我要删除的产品的 ID。

当我控制台日志 req.body 我得到: [对象:空原型] { productId: '' }

为什么会这样?删除产品后,我将我的页面重定向到“/admin/products”。

在 product.ejs 文件中,它应该是来自隐藏输入的 productId。

【问题讨论】:

  • 显示用于删除产品的 HTTP 请求
  • const express = require('express');常量路径 = 要求('路径');常量路由器 = express.Router(); //const rootDir = require('../util/path'); const adminController = require('../controllers/admin'); router.post('/delete-product',adminController.postDeleteProduct); // module.exports = 路由器; module.exports = 路由器; // 如果我们要导出多个,可以使用exports.router... //exports.products = products;
  • 为什么我的 prodId 为空??
  • 您展示了服务器端,但我要求来自客户端的请求。请将两者都添加到您的帖子中,而不是通过评论添加

标签: node.js npm sequelize.js


【解决方案1】:

真是个愚蠢的错误。 我在 product.ejs 文件中更改了它。

<input type="hidden" value="<% product.id %>" name="productId">

已改为

 <input type="hidden" value="<%= product.id %>" name="productId">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多