Search code examples
vue.jsaxiosvuejs3form-data

FormData is null but file is ok


(front vuejs3 + axios | back nodejs + prisma sql)

I have a function to create a post. When I use it with postman it works.

enter image description here

But when I use it with frontend it returns me a formdata = null

On this.selectedFile, i have the file

can you help me please ?

data () {
    return {
        title: '',
        content: '',
        userId: '',
        selectdFile: null,
    }
},
methods: {
    onFileSelected (event) {
        this.selectedFile = event.target.files[0];
        console.log(this.selectedFile);
    },
    async createPost() {
        const formData = new FormData();
        formData.append( 'image', this.selectedFile, this.selectedFile.name );

        console.log('ok')
        console.log(formData);
        const id = localStorage.getItem('userId');
        const response = await axios.post('http://localhost:3000/api/post', {
            title: this.title,
            content: this.content,
            userId: parseInt(id),
            attachment: formData,

        }, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('token')
            },
        });
        console.log(response);
    },

Voici le resultat : enter image description here


Solution

  • Try this:

    const response = await axios.postForm(
      "http://localhost:3000/api/post",
      {
        title: this.title,
        content: this.content,
        userId: parseInt(id),
        attachment: this.selectedFile,
      },
      {
        headers: {
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
      }
    );