How to connect frontend React code in Amplify to my spring backend API deployed in ElasticBeanstalk?

27 Views Asked by At

I'm using the fetch method in my React and the endpoint path used is the domain of my EC2 instance https://my-api.us-east-1.elasticbeanstalk.com/ (changed the URL to 'my-api' for obvious reasons).

When I make a direct request on the browser to https://my-api.us-east-1.elasticbeanstalk.com/api/ping it works fine. But when doing it from the fetch button on the React app (from the site https://my-endpoint.bleble.amplifyapp.com/) I see (failed) net::ERR_CONNECTION_REFUSED and no API call was made at all.

I only have my front deployed in Amplify and my backend on Elastic Beanstalk. (The idea is to deploy this app with the minimum required to function)


On postman, the backend endpoint works perfectly; is the frontend-backend connection the problem.


ConfigData.json

{
  "AWS_REST_ENDPOINT": "https://my-api.us-east-1.elasticbeanstalk.com"
}

Frontend Code

import configData from '../configData.json'

export async function getFitArb(data) {
    const response = await fetch(configData.AWS_REST_ENDPOINT + `/api/arb`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
      })

    if (!response.ok) {
      if (response.status === 500) {
        return {'resume':[]};
        throw new Error('Server Error');
      } else if (response.status === 404) {
        throw new Error('Resource Not Found');
      } else {
        throw new Error('Unknown Error');
      }
    }

    return await response.json();
}

Backend Controller

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/")
public class ArbController {
    
    private final ArbService arbitrageService;
    private final ConfigurationHolder configurationHolder;
    private final CustomSerializer serializer;


    @PostMapping("/arb")
    public ResponseEntity<?> createArbitrages(@RequestBody Inv inv) throws JsonProcessingException {

Tries:

  1. Started pointing to the http endpoint of the backend API (front the React code)
  2. Then I saw I needed to use the https one
  3. Added the mode: 'no-cors' on the frontend fetch method

None of these worked.

I expected: Frontend (from browser) [It's in Amplify service] -> Click on the fetch button -> Request to backend API in ElastickBeanstalk -> Returns response to the frontend -> Reloads browser info

0

There are 0 best solutions below