【问题标题】:Cannot read property 'Image' of undefined error on Nodejs无法读取 Nodejs 上未定义错误的属性“图像”
【发布时间】:2021-12-31 13:15:58
【问题描述】:

我正在尝试制作购物车。我正在制作管理面板,我需要在其中提交图像以添加产品。创建表单后

       <section>
      <div class="container mt-4">
        <div class="row">
          <div class="col-md-6">
            <h2 class="text-cnter">Add Product</h2>

            <form action="/admin/add-product" method="POST" enctype="multipart/form-data">

              <label for="">Name</label>
              <input type="text" name="Name" class="form-control">

              <label for="">Category</label>
              <input type="text" name="Category" class="form-control">

              <label for="">Price</label>
              <input type="text" name="Price" class="form-control">

              <label for="">Description</label>
              <input type="text" name="Description" class="form-control">

              <label for="">Image</label>
              <input type="file" class="form-control">

              <button class="btn btn-success mt-4" type="submit">Submit </button>

            </form>

          </div>


        </div>
      </div>
      </div>
    </section>

在 admin.js 文件中(管理员路由器所在的位置)

  

router.get('/add-products',function(req,res){
  res.render('admin/add-products')
});

// router.post('/add-product',function (req,res) {
//   console.log('Got it')
// });

router.post( "/add-product", function( req, res ) {

   console.log(req.body)
   console.log(req.file.Image)
  

});

module.exports = router;

app.js 文件

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var hbs = require('express-handlebars');
var fileupload =require('express-fileupload');

var bodyParser = require('body-parser');

var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
const {allowInsecurePrototypeAccess} = require('@handlebars/allow-prototype-access')
var multipart = require('connect-multiparty');

var multipartMiddleware = multipart();


var app = express();

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

//Layout Directory Set
app.engine('hbs',hbs.engine({ extname:'hbs' , defaultLayout:'layout',layoutsDir:__dirname+'/views/layout/',partialsDir:__dirname+'/views/partials'}));

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


app.use('/', userRouter);
app.use('/admin', adminRouter);

// 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;

使用 nodemon 运行后给出提交按钮显示

无法读取未定义的属性“图像”

TypeError: 无法读取未定义的属性“图像”

顺便说一句,我刚刚开始使用 nodejs。这就是为什么我不知道更多。

【问题讨论】:

  • req.file 不存在...您需要了解如何处理文件(我不知道)。另外,您想在 router.post("/add-product") 的末尾做出某种响应,否则请求将挂起。

标签: javascript html node.js


【解决方案1】:

您可能需要检查 admin.js 文件中的这一行: console.log(req.file.Image)

基于错误消息req.fileundefined,因此无法读取Image

原因是,express 需要额外的中间件来正确处理 multipart/form-data。查看Multer。这应该可以帮助您获取表单的所有部分,包括文件。

还请注意,您的文件输入没有相同。所以用Image肯定是找不到的。

【讨论】:

【解决方案2】:

好像req.file是未定义的,所以无法读取未定义的属性Image

【讨论】:

    【解决方案3】:

    尝试更改此设置。首先为您的输入文件提供一个名称

     <label for="">Image</label>
     <input type="file" name = "img" class="form-control">
    

    尝试获取文件然后使用

    router.post( "/add-product", function( req, res ) {
    
    console.log(req.body)
    console.log(req.files.img)
    
    
    });
    

    【讨论】:

    • 是的,谢谢它对我有用。
    猜你喜欢
    • 2021-10-04
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2014-09-02
    • 1970-01-01
    相关资源
    最近更新 更多