Home > OS >  How do i make an api call from react to my next.js backend on localhost?
How do i make an api call from react to my next.js backend on localhost?

Time:06-17

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!

CodePudding user response:

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

  • Related