How to add custom HTTP headers in React application?

Viewed 23237

I have a react js application. I want to add some http headers in the every response that's being returned from the app. Could you please suggest how to implement this !

NOTE : I am not trying to call any api with headers in request. I want my react app to respond with some custom headers in the response

2 Answers

As Dovlet Mamenov mentioned in the comment, this has to be done on the web server wherever react app is hosted.

For example, If react app is hosted on the Apache server, then these http headers in the response should be added on the Apache server conf.

const header = new Headers();
header.append('Access-Control-Allow-Origin', '*');

const body = {
  author: author,
  text: text
}

axios.post("https://api.test/posts/create", body, header)
  .then((res) => {
    this.setState({
      result: res
    });
  })
  .catch((error) => {
    this.setState({
      error: error.message
    });
  })

You have to use the native object Headers, and add it in axios.

Related