Mr.Gomer
Mr.Gomer

Reputation: 649

Creating a header in React

Is this a valid way to create a header in react ? as in adding the header constant the way i did. I pointed to the line with a arrow.

const upload = (file, onUploadProgress) => {
    let formData = new FormData();
  
    formData.append("file", file);
    const header = new Headers(authHeader());
    header.set('Accept', 'application/json');
    header.set('Content-Type', 'application/json');
    header.set("Content-Type", "multipart/form-data")
  
    return axios.post(API_URL + "upload", formData, {
      headers: header,      <---- this part.
      onUploadProgress,
    });
  };

Upvotes: 0

Views: 1481

Answers (2)

Chris Claude
Chris Claude

Reputation: 1372

As far as I can see if you do not plan on changing the state of your header, you are doing the right thing. The header object basically needs to be an object.

Here's what the axios API. It shouldn't change in react unless you want to do some state manipulation of the header object.

Upvotes: 1

amdev
amdev

Reputation: 7432

Yes, indeed!

if you are using post man, you can even configure an instance of your API, providing it some baseURL and some other options, including these casual HTTP headers, and after that you are not going to repeat it in each API call:

some thing like below:


// api.js file


import axios from 'axios'

const headers = new Headers(authHeader());
headers.set('Accept', 'application/json');
headers.set('Content-Type', 'application/json');
headers.set("Content-Type", "multipart/form-data")


export default axios.create({
 
  baseURL: YOUR_API_ENDPOINT,
  timeout: 1000,
  headers

})
  

it also provides you some other customer stuff like timeour configuration!

more info you can find here

Upvotes: 1

Related Questions