0

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,
    });
  };
1
  • Your question includes axios. Try adding an axios tag to your question. Commented May 3, 2021 at 15:22

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

8 Comments

any Ide why im getting this error. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
this is definitely related to your backend API provider developer, basically, they just disallow some origins to be reached to backend data and APIs, please check this with your backend guy :)
i am the backend and frontend guy :D its my project.
So in that case, you need to add a "Access-Control-Allow-Headers" to your responses like this file here github.com/a-m-dev/NodeJs_Simple_Restful_API/blob/master/src/… it's my node js template for the backend but this middleware is responsible for handling the CORS problem, which I think it's going to be useful in your case :)
ill see what i can get done thank you a lot.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.