1

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);
Jesus
  • 35
  • 6

3 Answers3

2

try changing headers of axios with

'content-type': 'multipart/form-data'
Mòe
  • 269
  • 2
  • 7
  • Thx Moe, i tried and i got a new error 'Boundary no found' and the solution to this error is to remove the 'content-type': 'multipart/form-data', so i go round in circles – Jesus Apr 25 '21 at 17:50
0

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);
Jesus
  • 35
  • 6
0

change your multer version and try it agian

npm i multer@2.0.0-rc.2

and edit this:

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