0

I have a couple of questions regarding how ReactJS should work in development and production. My ReactJS application was built starting from creare-react-app boilerplate. I have a SpringBoot backend listening on port 8080. The first thing I noticed is that if I set a code like this to make requests the code hang:

async componentDidMount() {
    ...
    const response = await fetch('http://localhost:8080/api/compliance');

I need to convert it into:

async componentDidMount() {
    ...
    const response = await fetch('/api/compliance');

and then add the line:

"proxy": "http://localhost:8080",

and this works fine. The problem is that when I put this in a pre-production environment (or integration environment) where I have a URL like http://www.mywebsite.com I got:

Invalid Host Header

Looking on the web I noticed that probably this could be to:

1. proxy that checks. the HTTP Header host and verify it to avoid security attacks
2. webpack package

I would like to understand:

1. Is proxy really necessary to let ReactJS app talk with its backend?
2. If no, how I can solve the issue (currently solution on the web didn't solve my problem)?
Salvatore D'angelo
  • 1,019
  • 3
  • 14
  • 39

1 Answers1

0

Generally proxy is not meant for production. Your app should provide both app and api on same port, on one server. https://stackoverflow.com/a/46771744/8522881

Fide
  • 1,127
  • 8
  • 7
  • Ok, that could make sense but it's not clear to me how to change my ReactJS app to avoid using the proxy. The link doesn't provide the answer if I well understand. You said "Your app should provide both app and API on the same port" but how they are two pieces of code totally different. My frontend is in ReactJS listening on 3000 port and my back is SpringBoot code listening on 8080 port. – Salvatore D'angelo Apr 28 '20 at 10:42
  • This is in development environment. In production you wil have to have server listening on port 80 to respond to first get request from user. And this first get request is responded with index.html with injected JavaScript code of your React app. This code you get with npm run build (or other building script in your CRA). And the same server that serves this request also processes your api requests. Try to first build your simple app without REST API. – Fide Apr 28 '20 at 11:04