0

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:

//code on nextJS

import axios from 'axios';

export default async function(req, res) {
    const apiData = await axios.get(
        `https://api.exchangerate.host/latest?base=${req.body.from}&symbols=${req.body.to}&places=3`
    );
    const dataKeys = Object.keys(apiData.data.rates);
    const newData = dataKeys.map((eachId) => {
        return apiData.data.rates[eachId];
    });
    const resRate = newData[0];

    res.json({ rate: resRate, date: apiData.data.date });
}

//Code on Create react app:

const testApi = () => {
        const body = {
            from: 'USA',
            to: 'ILS'
        };
        console.log(JSON.stringify(body));
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        };

        fetch('http://localhost:3000/api/getExchangeRate', requestOptions).then((response) => console.log(response));
    };


thanks in advance!
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sapir
  • 33
  • 1
  • 7
  • You need to configure CORS on your API routes, as API routes are same-origin only by default. See https://stackoverflow.com/questions/67922662/cors-error-when-making-network-call-in-useeffect-in-next-js for an example. – juliomalves Jun 22 '22 at 12:59

1 Answers1

1

You would probably need to install cors to your backend with the command

npm install cors 

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

wally
  • 58
  • 7
  • I'm afraid the problem persists: Access to fetch at 'http://localhost:3000/api/getExchangeRate' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I've installed cores on the backend and placed the code in _app.js file am I doing something wrong? – Sapir Jun 16 '22 at 18:28
  • By the way, the CRA by default should be running the front end on port 3000, that is, localhost:3000. – wally Jun 16 '22 at 18:55
  • thank you for the answer! I figured it out. taking some thoughts on the matter ill probably move to express.js anyway, figured next.js is probably too robust for being only a backend server. =] – Sapir Jun 16 '22 at 20:39