Fetch works, but only when using async behaviour.
I'm re-building an existing property booking website. It was created with Laravel and used a self-built API. I am re-building with React with Next JS (new to me). All of the property information comes from a remote API (not under my control).
/index.js Once you hit the browse page, you can browse properties. Then you choose a property. The data for the selected property and an initial calendar for this property comes from the API using this pattern:
export const getServerSideProps = async (context) => {
// Property detail
const res = await fetch(`https://remote_api_address_property_info_endpoint`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
},
})
const property = await res.json()
const res = await fetch(`https://remote_api_address_calendar_info_endpoint`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': auth
},
})
const calendar = await res.json()
return {
props: {
property,
calendar
}
}
}
The property and calendar data are fetched and I send the data as props to the 'View' page. This page renders out all of the data, including the calendar. The problem starts when I choose 'next' on the calendar, on this page to show the following (or previous) month. There's an inbuilt event hook in the calendar code (an npm calendar plugin) for when 'next' is clicked and I use that to run a function which attempts to bring in the following month's calendar data. I have used various versions of the code above to pull that data, feeding in the current month etc. to bring in the new data, but to no avail. For some reason, fetch now seems to pre-flight the request to the API but comes back with an error of 'failed to fetch' from the server. That's the only error message I can elicit from the server.
I have tried using async (and not). I have tried moving the request to its own apihelper.js file and including it with and without async, each time trying to return some results. I can use the generated url and auth string and get the data every time from Postman but not in this secondary situation (it still works on the inde.js page). Can anyone help with this? I feel it's something missing from the headers that the API doesn't like but after a few days, I'm all out of ideas. If I have to, I will try to contact the company and see if they'll check my incoming requests and tell me why they are being rejected but they're in a different time-zone and I'm not sure how helpful they'll be with this type of request from a programmer. Anyhow, any ideas I could try greatly appreciated.
This is the current iteration of the function. It has been through many changes including using async and not but this is the essence of it:
The calendar (using 'react-calendar') for some context:
<div className={styles.reactCalendar}>
<CalendarBox
className={styles.reactCalendarBox}
onChange={onChange}
selectRange="true"
returnValue="range"
minDate={new Date()}
tileDisabled={tileDisabled}
onActiveStartDateChange={onDateChange}
/>
The function called from the calendar 'next' link:
const onDateChange = async (startDateInward) => {
const result = await fetch(`https://api_endpoint_with_date_from_startDateInward`, {
method: 'GET',
headers: {
"Content-Type" : "application/json",
'Authorization': authorizationString
}
}).then(response => {
if(response.status >= 400) {
throw new Error("Server responds with error")
}
}).then(calendarInfo => {
console.log('got a result')
},
err => {
console.log('Error is: ', err.message)
})
return result
}
I noticed a difference in the user-agent from successful requests an non-successful. I include it here in case it adds a clue:
Request headers from Postman:
Succesful request: user-agent: "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"
Non-successful request: user-agent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"