Jesus
Jesus

Reputation: 35

multer : req.file is undefined

I want to send a file with axios, from my Vue.js to my Node.js, but the req.file parameter is never filled, it's undefined Here is the simplified code from my vue :

Inscription.vue :

<template>
  <div class="main_content">
  <h1>Inscription</h1>
  <div><input type='file' @change='openFile'></div>
  <button type='button' v-on:click="inscription" class="inscription">Inscription</button>
  </div>
</template>

<script>
import Axios from 'axios';
export default {
data () {
     return { selectedFile: null}
},
methods:{
    openFile (event) {
        this.selectedFile = event.target.files[0];
    },
    inscription () {
      let fd = new FormData();
      fd.append('avatarBase64', this.selectedFile);
      Axios.create({baseURL: 'http://localhost:4444'}).post('/api/testUploadImage', {avatarBase64: fd});
    }
}

My simplified node.js application :

main.ts

import express from "express";
var cors = require('cors');
var bodyParser = require('body-parser')
const multer = require('multer')
const http = require('http');

const server = express();
server.use(cors({origin: true}))
server.use(bodyParser.json({limit: '50mb', extended: true}));
server.use(
    bodyParser.urlencoded({
      extended: true
    })
  )

server.post("/api/testUploadImage", upload.single('avatarBase64'), async (req: any, res: any) => {
    // req.file is undefined PROBLEM THERE
});

const httpServer = http.createServer(server);
httpServer.listen(port);

Upvotes: 1

Views: 256

Answers (3)

daniel
daniel

Reputation: 89

change your multer version and try it agian

npm i [email protected]

and edit this:

    Axios.create({baseURL: 'http://localhost:4444'}).post('/api/testUploadImage', fd);

Upvotes: 0

Jesus
Jesus

Reputation: 35

I found out : i was sending this

Axios.create({baseURL: 'http://localhost:4444'}).post('/api/testUploadImage', {avatarBase64: fd});

instead of this :

Axios.create({baseURL: 'http://localhost:4444'}).post('/api/testUploadImage', fd);

Upvotes: 0

M&#242;e
M&#242;e

Reputation: 294

try changing headers of axios with

'content-type': 'multipart/form-data'

Upvotes: 2

Related Questions