How to add custom HTTP headers in React application?
Asked Answered
K

2

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

Kienan answered 4/10, 2019 at 9:11 Comment(3)
As far as I understand this should be done on a web server where react app is hosted.Phonolite
Related: #44355263Antiphony
If you are talking about your Dev env only check this questionStab
K
-1

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.

Kienan answered 2/12, 2020 at 10:53 Comment(1)
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.Antiphony
C
-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.

Coven answered 4/10, 2019 at 9:20 Comment(4)
What is this url in "axios.post("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 toolsKienan
Ok, I thought you wanted to post content to an API. The url was an example.Henn
nope. I want to add headers in the response of react appKienan
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' } }Upbraiding

© 2022 - 2024 — McMap. All rights reserved.