簡體   English   中英

ReactJS:POST 400(錯誤請求)使用 Axios

[英]ReactJS: POST 400 (Bad Request) using Axios

我正在使用 axios 來點擊 API 將 a.apk 文件上傳到在我的計算機上本地運行的第 3 方應用程序。 在 Postman 上使用 API 給出了預期的結果,但是在將它與我的 React 應用程序集成時,我收到POST http://localhost:8000/api/v1/upload 400 (Bad Request)錯誤。

我有以下結構:

src/httpRequest.js

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:8000",
  headers: {
    "Content-type": "application/json",
    Authorization: <API_KEY>
  }
});

源代碼/服務/Upload.js

import http from "../httpRequest";

const upload = (file, onUploadProgress) => {
  const formData = new FormData();
  formData.append("file", file);
  return http.post("/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
      Authorization:
      <API_KEY>
    },
    onUploadProgress,
  });
};

export default {
  upload,
};

源代碼/組件/ApkUpload.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const ApkUpload = () => {
  const [selectedFiles, setSelectedFiles] = useState(undefined);
  // eslint-disable-next-line no-unused-vars
  const [currentFile, setCurrentFile] = useState(undefined);
  const [progress, setProgress] = useState(0);
  const [message, setMessage] = useState('');
  const [fileDetails, setFileDetails] = useState([]);

  const handleUpload = async () => {
    const data = new FormData();
    data.append('file', selectedFiles);
    try {
      const res = await axios.post('http://localhost:8000/api/v1/upload', data, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: <API_KEY>,
        },
        onUploadProgress: (progressEvent) => {
          setProgress(parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total), 10));
        },
      });
    } catch (err) {
      if (err.response.status === 500) {
        setMessage('There was a problem with the server');
      } else {
        setMessage(err.response.data.message);
      }
    }
  };
  const handleChange = (e) => {
    setSelectedFiles(e.target.files);
    setCurrentFile(e.target.files[0]);
  };

  useEffect(() => {
    axios.get("http://localhost:8000/api/v1/scans", {
    headers: {
      Authorization:
        <API_KEY>,
    },
  }).then(res => {
    setFileDetails(res.data.content);
  });

  },[]);

  return (
    <div className="container">
      // simple button calling above methods
    </div>
  );
};
export default ApkUpload;


我正在使用 MobSF 作為我的第三方應用程序,並且要上傳它們需要 multipart/form-data。

在使用 postman 時,我能夠獲得所需的結果,但我無法通過我的前端實現。 非常感謝有關此問題的任何幫助!

const data = new FormData();
data.append('file', selectedFiles[0]);

在您的handleUpload function selectedFiles state 中屬於FileList類型,但它應該是File

如果您正在處理單個文件,那么您可以使用:

data.append('file', selectedFiles[0]);

對於多個文件,您可以執行以下操作:

for(let i=0;i<selectedFiles.length;++i){
 data.append('file',selectedFiles[i])
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM