My case: I'm developing a web application where a user can get information regarding traffic events, current traffic flow and information regarding flights that recently landed at specific airports. For a couple of reasons, I've incorporated Express.js to handle the requests from the frontend, get the data from the API in question, and then send the data back to the client.
THE PROBLEM:
Everything works fine in local development mode - all the API calls get called as expected, data is sent to the client as expected. In other words, everything is fine and dandy in development. In production mode, however, things are not OK. My POST routes (I have 2 POST routes) work as expected, but the remaining GET route doesn't work. Checking the Networks tab in Chrome DevTools, the request status code returns a 503.
I have a CRA application (using React Hooks), in which I have three components. Each of the components uses the fetch method to call an endpoint:
In FlightList.js:
import React, {useState, useEffect} from 'react';
import Wait from './Wait';
import './FlightList.scss';
export default function FlightList(props) {
const [flights, setFlights] = useState([]);
const [flightData, setflightData] = useState(false);
const [typeOfFlights, settypeOfFlights] = useState('LAN');
useEffect(() => {
fetch('/flights', {
method: 'GET',
headers: {
'Content-Type':'application/json'
}
})
.then(res => res.json())
.then(data => {
setFlights(data.flights)
setflightData(true)
}).catch(err => console.log(err))
}, []);
In server.js:
//production mode
if(process.env.NODE_ENV === 'production'){
app.use(express.static(path.join('./app/build')));
}
app.get('*', (req,res) =>{
res.sendFile(path.join(__dirname, './app/build'), 'index.html');
});
app.get('/flights', async (request, response) => {
await fetch(`https://api.swedavia.se/flightinfo/v2/query?filter=(airport eq 'ARN' or airport eq 'BMA') and flightType eq 'A' and flightStatus ne 'DEL' and (estimated ge '${date}T${agoDate.toLocaleTimeString()}' and estimated le '${date}T${futureDate.toLocaleTimeString()}')&count=800`, {
mode: "cors",
method: 'GET',
headers: {
'Ocp-Apim-Subscription-Key' : '(API KEY HERE)',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Host': 'api.swedavia.se',
'Access-Control-Allow-Origin': 'api.swedavia.se',
}
}).then(response => response.json())
.then((content) => response.send(content))
.catch(err => console.log(err))
});
Any suggestions? Have a great day, people!