What is the best way to send an API request from a React frontend to my Next.js backend running on localhost?

I have currently developed a create react app and I am interested in creating a next.js backend for it. I have set up an API route on the server-side which will fetch data from another API and generate a response accordingly. I do not want to fully migrate my app to nextJS. I have tested the API route using the "insomnia" API design platform and it seems to be working fine.

The next.js server is running on localhost:3000 and the CRA (create react app) is on localhost:3001. However, when I try to use 'Fetch' from the CRA, I encounter 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 can I resolve this issue? I apologize if there are any errors in my terminology, as API calls and nextJS are new concepts for me.

Code:

//nextJS code

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 });
}

//Create React App code:

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));
    };


Thank you in advance!

Answer №1

To enable cross-origin resource sharing in your backend, you will likely need to install the cors package using the following command:

npm install cors 

After installing, incorporate the middleware into your backend's app.js file like so:

const cors = require('cors')

app.use(cors())

For more information on CORS, please refer to this link: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

I hope this information proves helpful.

Don't forget to add this configuration to the front end app's package.json file:

"scripts": { // ... }, "proxy": "http://localhost:3000"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for dynamically loading mui icons from mui with TypeScript

Is it possible to dynamically load MUI icons based on a string parameter using the following code snippet? import Icon from "@mui/icons-material" import SvgIcon from '@mui/material/SvgIcon'; const IconComponent = (props: typeof SvgIco ...

In my attempt to install and require the packages "fs," "path," and "js-yaml" on my Windows 10 system, I encountered an issue. Specifically, only the "js-yaml" package resulted in the error message "

 Greetings! I am new to the world of computers and have been enjoying the insightful Q&As on this platform. This is my debut question on StackOverFlow, so please bear with me if my technical jargon or English seems a bit off.  I spent several hour ...

Issue with Puppeteer - Element not visible on the screen

While using Puppeteer in NodeJS to capture a screenshot of the Google Flights page, I encountered an issue where one element does not appear when the browser is launched with Puppeteer. However, when I access the same URL/link in any other browser without ...

Ensure that the memory usage of each process in Node.js is restricted to under 300MB

We execute tests in different instances and some of our test suites consist of more than 20 files. Is there a way to restrict the memory usage of a Node.js process to less than 300MB instead of allowing it to grow? If we don't set any limits, each pro ...

The performance of the simple-peer package is not meeting expectations

I've been working on integrating the simple-peer package into my Meteor application for implementing voice chat. Here's a snippet of how I'm using the package: 'click #btnCall ': function(e, t) { e.preventDefault(); ...

"Sending an array in a POST request using Javascript and processing it on the server

I am trying to use ajax to send an array. Let's say the array looks like this: var anotherOne = 'anotherOneData'; var documents = ['banana', 'apple', 'monkey']; I successfully sent both a normal value and an a ...

I'm having trouble locating the airtable module, even after I successfully ran npm install airtable

Currently attempting to integrate the airtable api into my website's backend using node.js. However, upon writing var Airtable = require('airtable'); and running the file with node [filepath], I encounter an error in the command prompt: ...

Using request-promise from npm, send a request with a self-generated certificate in JavaScript

When trying to make a simple request using the request-promise library, I encountered an error due to having a self-signed cert in my chain. This is a requirement that cannot be avoided. Fortunately, with NPM, I was able to specify the cert for installing ...

I'm having trouble locating the socket.io.js file when using Node.js with Express and Socket.IO

While working on a node js application that involved socket.io, I sought help from SO but couldn't find a solution for my specific issue. The error message I encountered is as follows: Failed to load resource: the server responded with a status of 4 ...

Issue with installing Gulp using Laravel Homestead and Elixir

While attempting to run npm install in homestead, I encountered a lengthy list of errors that started with npm ERR! UNKNOWN, mkdir '/home/vagrant/Code/gulp/node_modules/gulp-imagemin/node_modules/imagemin/node_modules/imagemin-optipng/node_modules/o ...

What is the solution to the error message that states a bind message provides 4 parameters, while a prepared statement "" necessitates 5?

Is there a way to fix the issue where the bind message provides 4 parameters but the prepared statement "" requires 5? I've tried solutions from others who faced similar problems without success. (I've included all classes for better error unders ...

Docker containers do not allow environment variables to be overridden

I am relatively new to Docker and I have a Nextjs application running inside a docker container. This application utilizes certain environment variables for communication with the server. An issue arises where, despite passing the environment variables whe ...

The environment variable was not properly included in the container's environment

Behold, my Dockefile FROM ubuntu:latest MAINTAINER mazzy WORKDIR /tmp RUN apt-get update && apt-get install -y wget RUN wget http://nodejs.org/dist/v0.12.0/node-v0.12.0-linux-x64.tar.gz RUN tar xvf node-v0.12.0-linux-x64.tar.gz RUN cp -r node- ...

What is preventing the bundling of my CSS into the application?

I'm facing an issue while setting up a new project using vue.js, scss, and webpack (with express.js on the server side and TypeScript). I copied over the configurations from a previous project where everything was working fine. According to my underst ...

The function initFoodModel is missing and causing issues as it tries to read properties of undefined, specifically attempting to read 'findAll'

myWishlist.js const { setupFoodModel } = require("../../model/FoodModel"); const { setupWishlistModel } = require("../../model/myWishlistModel"); const setupMyWishlistModel = async () =\> { try { const sequelizeConnection = awai ...

Guide to using Node.js to efficiently add documents to several collections in a single query

I am exploring the possibility of inserting documents into multiple collections with a single query. Let's say I have two collections named person and address. My goal is to insert documents into both collections using just one query. Specifically, d ...

What steps can I take to resolve the hydration issue with the authenticating component?

My current setup involves an authentication component that verifies whether the user has a token stored in local storage. Below is a snippet of the code: import { useRouter } from "next/router"; import { useState } from "react"; const ...

Error: Docker unable to locate package.json file

I'm encountering an issue. I tried building a project in Docker and received an error. The error states that during npm install, the package.json file could not be found. Here is my Dockerfile: FROM node #copy source COPY . /app # Install dependenc ...

Having trouble retrieving data from the PokeAPI

Currently, I am experimenting with PokeAPI for educational purposes and attempting to run the following code: const express = require('express') const https = require('https') const app = express() const port = 3000 app.get('/&apo ...

Differences in mounted volumes between using "up" and "run" in docker-compose

Update Alert 2: I've developed a demo project on GitHub to replicate this issue. After further testing, the scenario is slightly different from what I initially explained. Below you'll find the details of the README I created on the GitHub repos ...