node.js .getHeaders() 在反应中的等价物是什么? (文件上传与 axios 反应)

What is the equivalent of node.js .getHeaders() in react? (file upload in react with axios)

我尝试向 api 发出补丁请求,以便上传一个文件,我可以使用 Postman 使其工作,但不能在我使用 axios 的反应项目中使用。 (响应状态为 200,但我尝试上传的文件未上传)。

所以我检查了邮递员为该请求生成的代码(它是为 node.js 生成的),与我所做的似乎不同的是 headers 除了

'Content-Type': 'application/json', 
'Authorization': 'Bearer randomstring.randomstring.randomstring',

他还使用 FormData 中的 headers。那么在 React 中 formData.getHeaders() 相当于什么?

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('userImageFile', fs.createReadStream('/C:/Users/George/Downloads/dummy.jpg'));

var config = {
  method: 'patch',
  url: 'https://api.services.thenameoftheapi.net/api/v3/billing/cebfecea-ff40-4e1f-9fb0-ca588496c787/',
  headers: { 
    'Content-Type': 'application/json', 
    'Authorization': 'Bearer randomstring.randomstring.randomstring', 
    ...data.getHeaders()
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

PS:还有 headers .getHeaders() 从表单数据中提取的内容 如果表单数据只包含我上传的文件?

var userImageFile;

function onFileFormSubmit(e) {
  e.preventDefault();
  const formData = new FormData();
  formData.append("userimage", userImageFile);
  // var headers = formData.getHeaders() // what would headers contain?
  props.patchUser(formData); //redux saga flow
}

function onFileChange(e) {
  userImageFile= e.target.files[0]
  e.target.nextSibling.click(); // To submit the form
}

// an in return of react component the form is the following
<form onSubmit={onFileFormSubmit}>
   <label htmlFor={"upload" + i} className="table_upload">Upload</label>
   <input className="d-none" id={"upload" + i} onChange={onFileChange} type="file"></input>
   <button className="d-none" type="submit"></button>
</form>

实际提出补丁请求的代码如下

import axios from "axios"

const axiosApi = axios.create({
    baseURL: 'https://api.services.thenameoftheapi.net/api/v3',
    'Authorization': 'Bearer '
})

axiosApi.interceptors.request.use(function (config) {

    let access_token = localStorage.getItem("accessToken");
    config.headers = {
      ...config.headers,
      'Authorization': 'Bearer ' + access_token
    }
    config = {...config, Authorization: 'Bearer ' + access_token}
    return config;
  });


export async function patch(url, data, config = {}) {
    console.log('url = ', url); // This outputs correct url
    console.log('data = ', data); // This outputs FormData {}
    console.log('config = ', config); // Empty now but exists to pass parameters if needed
    var headers = {};
    for (var pair of data.entries()) {
        console.log(pair[0]+ ', ' + pair[1]);     // This outputs userimage, [object File]
    }
  
    if ('headers' in config && config.headers ) {
      headers = config.headers
      delete config.headers;
    }
    return axiosApi
      .patch(url, { ...data }, { params: { ...config }, headers: headers })
      .then( response => response.data)
  }

你在用 header 做一些奇怪的事情。这是一个稍微简化的版本,理论上应该可以工作 as-is:

import axios from "axios";

const axiosApi = axios.create({
  baseURL: 'https://api.services.thenameoftheapi.net/api/v3'
});

axiosApi.interceptors.request.use(function (config) {
  config.headers = {
    ...config.headers,
    'Authorization': 'Bearer ' + localStorage.getItem("accessToken")
  };
  return config;
});

// I renamed "config" to "params", to avoid confusion
export function patch(url, data, params = {}) {
  let headers = {};

  if (params.headers) {
    headers = params.headers
    delete params.headers;
  }

  // Here, don't do { ...data }, you are destroying the FormData instance!
  return axiosApi
    .patch(url, data, { params, headers })
    .then(({ data }) => data)
}

这将导致请求具有此 header:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryxXxXxXx