Arxidiaris
Arxidiaris

Reputation: 51

Sending a csv from front-end to backend using axios

I am trying to send a csv file from my front end in reactjs to my back end in nodejs using axios. This csv file is selected via a browse UI button and stored in state using react. After searching online this is my code for the HTTPS request:

let formmData = new FormData();
formData.append('file', this.state.selectedFile);
           
const {data : QueryResult} = await axios({
    method: 'post',
    url: "https://localhost:...",
    formData,
});

Note: this.state.selectedFile contains an object which when logged on console is:

File {name: "MyFile.csv", lastModified: 1614958303483, …}

I also would like to say that this endpoint works fine when using Postman as seen below:

enter image description here

After printing the request in my back-end in the case this request from my frontend I see:

body: {}

I don't understand what I am doing wrong and this passes nothing to my back-end.

I also saw that this was an open issue with axios on GitHub in the past.

Can this be achieved now with axios or should i use another module? Any ideas?

Upvotes: 5

Views: 1998

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19813

You need to do:

await axios({
  method: 'post',
  url: "https://localhost:...",
  data: formData
});

because when you write just "formData", it becomes : { formData: formData } as per (new ES2015 object shorthand property name).

You can also use:

await axios.post('your_url', formData) 

Upvotes: 3

Related Questions