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

3
  • 3
    As far as I understand this should be done on a web server where react app is hosted. Commented Oct 14, 2020 at 5:54
  • Related: stackoverflow.com/questions/44354763/… Commented Aug 31, 2022 at 9:12
  • If you are talking about your Dev env only check this question Commented Dec 3, 2022 at 22:22

2 Answers 2

-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.

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

1 Comment

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.
-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.

4 Comments

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 tools
Ok, I thought you wanted to post content to an API. The url was an example.
nope. I want to add headers in the response of react app
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' } }

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.