Reputation: 5761
I have an express server set up like so:
app.get('/', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
fetch('https://api.adzuna.com:443/v1/api/property/gb/search/1?app_id=1cd4129d&app_key=key&where=se16bx&distance=5&category=for-sale')
.then(response => response.json())
.then(data => {
res.send(data) // Prints result from `response.json()` in getRequest
})
.catch(error => console.error(error))
});
I then have a Next.js page like so:
class About extends Component {
state = {postcode: null}
handleOnSubmit = e => {
// calling the api passing the postcode
}
render() {
return(
<form>
<input name="postcode" />
<button onClick={this.handleOnSubmit}></button>
</form>
)
}
}
About.getInitialProps = async function() {
const res = await fetch('http://localhost:3001/');
const data = await res.json();
return {
results: data
}
}
the API call in the Express server has a hard coded postcode in it.
where=se16bx
How can I pass that value in a dynamic way based on what the user will put into the form?
Thanks
Upvotes: 0
Views: 743
Reputation: 8228
Yes you can create dynamic API call, for complete documentation you can see from here (Check /posts
API).
In your case, you just need to add slug into your endpoint, then pass it to your fetcher function:
app.get('/:id*', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
fetch(`https://api.adzuna.com:443/v1/api/property/gb/search/1?app_id=1cd4129d&app_key=key&where=${req.params.id}&distance=5&category=for-sale`)
.then(response => response.json())
.then(data => {
res.send(data) // Prints result from `response.json()` in getRequest
})
.catch(error => console.error(error))
});
Upvotes: 1