9

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

Jesse Nickles
  • 1,435
  • 1
  • 17
  • 25
i.am.jabi
  • 620
  • 1
  • 5
  • 23

2 Answers2

0

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.

i.am.jabi
  • 620
  • 1
  • 5
  • 23
  • This is sort of a non-answer to the question, hopefully someone can provide an example of how React might work with Nginx/Apache to do this. – Jesse Nickles Aug 31 '22 at 19:11
-4
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.

  • 1
    What is this url in "axios.post("https://api.test/posts/create", body, header)" . I'm not calling any api. I have a web app( a react app ) that's being invoked from the browser. I want to add response headers and see the headers in the browser dev tools – i.am.jabi Oct 04 '19 at 09:36
  • Ok, I thought you wanted to post content to an API. The url was an example. – Rémi Rodrigues Oct 04 '19 at 12:20
  • nope. I want to add headers in the response of react app – i.am.jabi Oct 04 '19 at 13:05
  • This is absolutely not correct, you are trying to add a response header in request headers, this is not doable! BTW the syntax is not correct, you need to pass an object as the third parameter like this: {headers: { 'SOME_HEADER_KEY': 'SOME_VALUE' } } – Arman Safikhani Mar 20 '20 at 14:35