【问题标题】:Not able to send http POST request using axios无法使用 axios 发送 http POST 请求
【发布时间】:2022-01-15 15:42:25
【问题描述】:

我正在使用 MERN 堆栈构建 CSV 上传器。使用 axios 进行 api hit 和 multer 处理文件上传。当我尝试使用我的客户端发送 csv 文件时,我收到了 BAD REQUEST 错误。 但是当我尝试通过thunderclient用我的文件访问同一个端点时,它工作得很好,我在req.file对象下接收我的文件,但是通过axios客户端请求我在我的req.body对象中接收到这个。

 body: [Object: null prototype] { myfile: '[object FileList]' }


//Client Side

import React, {useState} from 'react'
import axios from 'axios'
import './App.css';
const App = () => {
 const [csv, setCsv] = useState({
  file: null
 })
const onFormSubmit = (e) => {
 e.preventDefault();
 const formData = new FormData();
 formData.append('myfile', csv.file);
 const config = {
   headers: {
    'content-type': 'multipart/form-data'
   }
 };
 axios.post("http://localhost:5000/csv_uploader", formData, config)
   .then((response) => {
     alert("The file is successfully uploaded");
   }).catch((error) => {
  });
}

const onChange = (e) => {
setCsv({ file: e.target.files });
}

return (
  <form onSubmit={onFormSubmit}>
   <h1>File Upload</h1>
   <input type="file" className="custom-file-input" name="myfile" onChange= 
   {onChange} />
  {console.log(csv.file)}
  <button className="upload-button" type="submit">Upload to DB</button>
 </form>
 )
}
export default App;



//Server Side
const storage = multer.diskStorage({
 destination: function (req, file, cb) {
   cb(null, __basedir + '/uploads/')
 },
 filename: function (req, file, cb) {
   cb(null, file.filename + "-" + Date.now() + "-" + file.originalname)
 }
})
const csvFilter = (req, file, cb) => {
 file.mimetype.includes('csv') ? cb(null, true) :
   cb('Please upload csv file', false);
}

const upload = multer({ storage: storage, fileFilter: csvFilter });

app.post('/csv_uploader', upload.single('myfile'), async (req, res) => {
 try {
    if (req.file == undefined) return res.status(400).send({ message: "Please 
    upload a csv file" });
    res.send('CSV UPLOADED');
 } catch (error) {
    console.log(error.message);
 }
})

在浏览器控制台中显示错误 xhr.js:210 POST http://localhost:5000/csv_uploader 400 (Bad Request)

响应 {"message":"Please upload a csv file"}

请让我知道我做错了什么。 提前感谢

【问题讨论】:

    标签: node.js reactjs api axios mern


    【解决方案1】:

    这里有一些你可以尝试的方法。

    1. upload.single('myfile') 更改为upload.single('myImage') 以匹配输入元素的名称属性
    2. 在服务器上记录请求并确保根本没有收到文件
    3. 删除multer fileFilter
    4. 将 Thunderclient 请求正文添加到您的问题中,以便读者获得成功请求的示例

    【讨论】:

    • 我尝试了所有的更改,但没有成功,还用 Thunderclient 正文和 req 对象的控制台日志编辑了问题
    • 尝试将 formData.append('myfile', csv.file) 的参数更改为 ('myfile', csv)。或者尝试发送文件,而不是 formdata 的一部分,即 axios.post('...',csv.file)。还可以尝试删除 req 标头,看看它们是否只是被推断出来。
    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多