【问题标题】:req not defined after muti-image form submission from angular从角度提交多图像表单后未定义请求
【发布时间】:2019-04-20 01:05:14
【问题描述】:

我正在尝试使用 Multer 作为我的中间件和 Express.json() 作为我的 bodyParser 从 Angular 7 提交一个包含文本和图像的表单到节点后端。表单数据在前端提交,文本数据在后端,但图像字段为空 {}。我试过使用 bodyParse.json() 并且结果是一样的。

这是我的 app.js 文件

const express = require('express');
// const bodyParser = require('body-parser');
const adminController = require('./controllers/admin');
const path = require('path');
const cors = require('cors')
const app = express()
const FORM_URLENCODED = 'multipart/form-data';
app.use(cors())

... my mongodb connection string ...

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X- Auth-Token')
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
  next();
});

// const bp = bodyParser.json()
// console.log('TCL: bp', bp);
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(express.static(path.join(__dirname, 'images')));

// req is not defined?!?!?!?!?
app.use(() => {
  if (req.headers['content-type'] === FORM_URLENCODED) {
    let body = '';
    req.on('data', chunk => {
        body += chunk.toString(); // convert Buffer to string
    });
    req.on('end', () => {
        console.log(body);
        res.end('ok');
    });
  }
})

// -- multer
const multer = require('multer');
const crypto = require("crypto");
const imgDir = 'images';

const imgStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'images')
  },
  filename: function(req, file, callback) {
    crypto.pseudoRandomBytes(16, function(err, raw) {
      if (err) return callback(err);
      callback(null, raw.toString('hex') + 
path.extname(file.originalname));
    });
  }
});

const fileFilter = ((req, file, cb) => {
  // accept image only
  if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
    return cb(new Error('Only image files are allowed!'), false);
  }
  cb(null, true);
});

const upload = multer({dest: imgDir, storage: imgStorage, fileFilter: 
fileFilter, limits: {fileSize: 16000} }).array('image',20);

// app.use(
//   upload.fields([
//     { name: 'mainImg', maxCount: 1 },
//     { name: 'image', maxCount: 5 },
//   ])
// );
// -- end multer

app.post('/admin/add-product', function (req, res, next) {
  var path = '';
  upload({dest: imgDir, storage: imgStorage, fileFilter: fileFilter, 
limits: {fileSize: 16000} });
    path = req.file.path;

/// path is not defined!?!?!?!?

    return res.send("Upload Completed for "+path);
}, adminController.postAddProduct);

const userRoutes = require('./routes/user');
app.use('/user', userRoutes);

module.exports = multer;
module.exports.imgStorage = imgStorage;
module.exports = app;

角形

<form [formGroup]="prodForm" (ngSubmit)="onSubmit()" enctype="multipart/form-data">
<div class="col-md-4">
      <label for="title"> <span class="required">*</span>Title: </label>
      <mat-form-field>
        <input class="form-control" matInput type="text" formControlName="title" #prodTitle />
        <mat-error *ngIf="prodForm.get('title').invalid">Please enter a title</mat-error>
      </mat-form-field>
    </div>
<div class="col-md-4">
      <div class="col-md-5">
        <button class="btn btn-success" mat-stroked-button type="button" (click)="filePicker.click()">
          Pick Image
        </button>
        <input type="file" #filePicker name="image" (change)="onImagePicked($event)" />
      </div>

      <div class="image-preview col-md-7" *ngIf="imgSrc !== '' && imgSrc">
        <img [src]="imgSrc" alt="{{ prodTitle.value }}" />
      </div>
    </div>

    <div class="col-md-12 sectButtons">
      <button class="btn btn-success" (click)="onShowStep2()">Next Step</button>
      <div class="clear"></div>
    </div>

角度形式输出

image: File {name: "some-image.jpg", lastModified: 1552012800142, 
lastModifiedDate: Thu Mar 07 2019 21:40:00 GMT-0500 (Eastern Standard Time), webkitRelativePath: "", size: 42381, …}
title: "some title"

节点控制器输出

TCL: exports.postAddProduct -> req.body { _id: '',
  title: 'some title',
  image: {}, }
TCL: exports.postAddProduct -> files undefined

我错过了什么?我花了太多时间试图弄清楚这一点。

【问题讨论】:

    标签: node.js typescript express angular7


    【解决方案1】:

    req 未定义,因为您尚未定义 req 对象。它不是有效的快递middleware。改为

    // next is optional
    app.use((req, res, next) => {
      if (req.headers['content-type'] === FORM_URLENCODED) {
        let body = '';
        req.on('data', chunk => {
          body += chunk.toString(); // convert Buffer to string
        });
        req.on('end', () => {
          console.log(body);
          res.end('ok');
        });
      }
    })
    

    【讨论】:

    • 我试过图像字段仍然以 {} 的形式出现。我想这可能是我处理组件中文件的方式。我不知道还有什么问题。
    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2021-06-24
    • 2014-02-15
    相关资源
    最近更新 更多