Req.body not available in multer.diskStorage(). Error Property body doesn't exist on type 'Request'

天涯浪子 提交于 2020-02-06 09:38:44

问题


I am trying to save files to local storage using Multer and what I want to do is specify the file name based on the fields in req.body.

Basically, the filename should be something like contractorId-projctId. But VS Code shows the error that body property is not defined on req and when I send the file it saves it as undefined-undefined.png. Here is a screenshot of my code. I've added this screen shot to highlight the fact that VS Code is screaming about req.body.

Here is the code for uploadFiles.js

// @ts-check
import express from 'express';
import bodyParser from 'body-parser';
import router from './routes/router';

const app = express();

// Setting up middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: '15mb' }));


// Setting up routes
app.use('/', router);

// Error handling
app.use('*', (req, res) => {
  res.status(404).json({
    code: 404,
    error: 'Not found',
    msg: "The resource you're looking for doesn't exist",
  });
});

export default app;

I've searched the stack overflow for similar questions but the most question are related to file uploads. The file is being uploaded just fine and I've tested that req.body is also fine, by sending a response back to postman. Here is the request.

Here is my code in router.js.

// @ts-check
import Router from 'express';
import upload from '../configs/filesUploads';

const router = Router();

router.get('/', (req, res) => {
  res.json({ Okay: true });
});

router.post('/uploads', (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      res.json({
        error: err,
      });
    } else {
      console.log(req.file);
      res.json({ test: 'Meh', body: req.body });
    }
  });
});
export default router;

Here is app.js

// @ts-check
import express from 'express';
import bodyParser from 'body-parser';
import router from './routes/router';

const app = express();

// Setting up middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: '15mb' }));


// Setting up routes
app.use('/', router);

// Error handling
app.use('*', (req, res) => {
  res.status(404).json({
    code: 404,
    error: 'Not found',
    msg: "The resource you're looking for doesn't exist",
  });
});

export default app;

回答1:


From multer documentation:

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

Try to rearrange your POST body fields by putting projectId and contractorId first, and the file upload at the end.



来源:https://stackoverflow.com/questions/54424057/req-body-not-available-in-multer-diskstorage-error-property-body-doesnt-exis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!