简体   繁体   English

使用 axios 从前端向后端发送 csv

[英]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.我正在尝试使用 axios 将 csv 文件从我在 reactjs 中的前端发送到我在 nodejs 中的后端。 This csv file is selected via a browse UI button and stored in state using react.这个 csv 文件是通过浏览 UI 按钮选择的,并使用 react 存储在 state 中。 After searching online this is my code for the HTTPS request:在线搜索后,这是我的 HTTPS 请求代码:

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:注意: this.state.selectedFile包含一个 object,登录控制台时为:

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

I also would like to say that this endpoint works fine when using Postman as seen below:我还想说,当使用 Postman 时,此端点工作正常,如下所示:

在此处输入图像描述

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.我还看到这是过去 GitHub 上的 axios 的未解决问题。

Can this be achieved now with axios or should i use another module?现在可以使用 axios 实现这一点,还是应该使用其他模块? Any ideas?有任何想法吗?

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).因为当你只写“formData”时,它变成: { formData: formData }按照(新的 ES2015 object 速记属性名称)。

You can also use:您还可以使用:

await axios.post('your_url', formData) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM