• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How do i make an api call from react to my next.js backend on localhost?

Resolved: How do i make an api call from react to my next.js backend on localhost?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I’v built a create react app atm and id like to build a next.js backend for it. I’ve created an API route on the server-side that will make another API call and create a response accordingly. I don’t want to migrate my app to nextJS completely. I know the API route works because I do get a response on the “insomnia” API design platform.
the server (next.js) is on localhost:3000 and the CRA is on localhost:3001, when I try to use ‘Fetch’ from CRA I get an error in the console: “Access to fetch at ‘http://localhost:3000/api/getExchangeRate’ from origin ‘http://localhost:3001’ has been blocked by CORS policy”.
How do I get it to work? I’m sorry in advance if I made some terminology mistakes, API calls and nextJS are super new to me.
Code:

Answer:

You would probably need to install cors to your backend with the command
Take the middleware to use in your backend app.js as follows

const cors = require(‘cors’) app.use(cors())


You can read more about CORS here: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Hope this helps.
Add this to the package.json file of the front end app
scripts": { // ... }, "proxy": "http://localhost:3000

If you have better answer, please add a comment about this, thank you!

create-react-app next.js node.js rest
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Sort dataframe columns value by close it to another column

27/03/2023

Resolved: PostgreSQL resample 1 minute OHLCV candle data into 5 minute OHLCV candle data

27/03/2023

Resolved: How do I navigate a table without any easily accessible distinctions?

27/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.