Addressing the data transfer issue between Spring framework and Next.js using Axios

For my upcoming project, I am considering using a combination of Spring and Next.js.

In the past, I have worked on projects using Spring and React.

I find the API/route structure in Next.js 13 version to be quite intriguing compared to traditional React frameworks.

When working with React, I typically follow a container-presentational pattern and write axios code in container components.

While this approach is possible in Next.js as well, I am interested in leveraging Next's API/route structure for data manipulation.

Furthermore, utilizing Next's structure seems to offer additional security benefits.

The challenge I am facing is passing data in the following sequence:

Spring -> api/route -> pageComponent

I can pass data successfully in the following sequences:

Spring -> pageComponent

api/route -> pageComponent

Below are snippets of my code:

--- Spring

@Configuration
public class WebMvcConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "DELETE").allowedOrigins("http://192.168.0.8:3000");
            }
        };
    }
}
@RestController
public class MainController {
    @GetMapping("/firstCall")  
    @ResponseBody
    public HashMap<String,Object> firstCall(){
        HashMap<String,Object> map = new HashMap<String,Object>();    
        map.put("age", 24);
        map.put("name", "mangdo");
        return map;
    }

}

--- Next

//route.ts
import axios from "axios"
export async function GET(request: Request) {
  let call = await callAxios()
  return call
}

async function callAxios(){
  const result = await axios.get('http://localhost:8080/firstCall', {
    params: { // query string
      title: 'NEXT JS'
    },
    headers: {
      'X-Api-Key': 'my-api-key'
    }
  })
  return result.data
}
//page.tsx
export default async function Home() {
  const res = await fetch(`http://localhost:3000/api/hello`)
  const jsonData = res

  console.log('res')
  console.log(JSON.parse(JSON.stringify(jsonData)))

  //show res {}
  return (
    <main className={styles.main}>
    
    </main>
  )
}

Please help me solve the data transfer problem between Spring and NextJS.

Answer №1

It appears that the app/api fetch can be utilized by the same Node.js frontend server internally, which is why it did not return any backend data. As a solution, I implemented client-side Axios code to make the backend data call.

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

Calculator app with Next.js: Using keyboard input resets the current number state in real-time

While developing a basic calculator application with Next.js, I encountered an issue. The functionality works correctly when the user interacts with the HTML buttons, but when trying to input numbers using the keyboard, the state resets to 0 before display ...

The shared module for next/router is not found in the shared scope default within Next.js and @module-federation/nextjs-mf

I am working on a JavaScript Turbo repo with a host app that has the following configuration in its next.config.js: const { NextFederationPlugin } = require("@module-federation/nextjs-mf"); const nextConfig = { reactStrictMode: true, ...

Error 406 – Unacceptable Response in Spring MVC and AngularJS: What You Need to Know

HTTP Status 406 – Not Acceptable The server cannot provide a response that is acceptable to the client according to the request headers, and it does not have a default representation. sample controller code @RequestMapping(value="/welcomes", method = R ...

Utilizing Axios for Submitting Form Data: A Step-by-Step Guide

Currently, I am in the process of developing a project that consists of a springboot backend and Vue frontend. At this point, I have successfully managed to retrieve a list of products from my database using GET requests. While I can display this list on a ...

Issue with the onClick event in next.js and TypeScript

While working on the frontend development of an app, I encountered a strange issue with the onClick function. The error message I'm seeing is: Type '(e: SyntheticEvent<Element, Event>) => void' is not assignable to type 'Custom ...

Exploring the Magic of Organizing Styled Component Constants in Visual Studio Code

After trying out Styled Components in NextJS/React, I have come to appreciate its benefits. Although I usually separate my styles into different js files, my limited experience with React, props, hooks, and context sometimes requires me to keep the styles ...

Deactivate any days occurring prior to or following the specified dates

I need assistance restricting the user to choose dates within a specific range using react day picker. Dates outside this range should be disabled to prevent selection. Below is my DateRange component that receives date values as strings like 2022-07-15 th ...

Reat is having trouble sending a POST request to a Spring Boot application

Encountering an issue: I have a Spring Boot API set up with various endpoints and a filter to determine access with or without a JSON Web Token. Postman works as expected, returning the correct data, but React seems to struggle with it. The root cause of t ...

Struggling with converting blob file to an image within a NextJS application using data from a MySQL database

Currently, I am in the process of working on a project where I need to retrieve an image stored as a blob file in my database. However, for some reason, the image is not displaying properly. Here is the code snippet from the first file, products.jsx: impo ...

Front-end user authentication concerns when employing JWT

Currently, my focus is on transitioning to the MERN stack and incorporating an authentication module using Next.js (front-end) + Node.js (for scalability). I am utilizing JWT token method for authentication and have some concerns: Storing tokens in coo ...

Dealing with Cross-Origin Resource Sharing (CORS) problem when using Google Cloud Storage Signed

I'm looking to empower artist clients to easily upload images to Cloud Storage by utilizing Signed URLs. Here's the backend script used to fetch the signed URL, which resides behind a Google Cloud load balancer: (Does the presence of a load bal ...

Low scoring performance in Lighthouse on a nearly empty page built with Next.js

While working on my Next.js project locally, I used npm run dev for development. After testing my website, I noticed that it scored a 40 in Performance. https://i.stack.imgur.com/3jmro.png Despite trying to use Lighthouse in secret mode, the results rem ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...

Troubleshooting Next.js server actions with ESLint error detection

I encountered eslint errors while developing a basic server component with server action: // /app/search/page.tsx export default function Search() { async function updateResults(formData: FormData) { "use server"; await new Promise((r ...

Creating a web application using Aframe and NextJs with typescript without the use of tags

I'm still trying to wrap my head around Aframe. I managed to load it, but I'm having trouble using the tags I want, such as and I can't figure out how to load a model with an Entity or make it animate. Something must be off in my approach. ...

What disadvantages should be considered when opting for Next.js over plain React for serverside rendering?

We are contemplating a rewrite of our React app to incorporate server-side rendering and have recently learned about Next.js. It appears to be a promising solution that offers seamless integration right from the start (routing, webpack, etc) with minimal ...

Issue with passing server components as props to client components not resolved

An error is occurring when attempting to pass a server component as props to a client component in a Next.js v14 implementation using next-auth v5. The pattern being followed is from the Next site at https://nextjs.org/docs/app/building-your-application/re ...

JSON is not being parsed in Next.js

Encountering an issue where Next.js parses JSON in development mode, but uses the json state in production mode. It's quite amazing! Check out the configuration file config.next.js below: const {webpack} = require("next/dist/compiled/webpack/webp ...

Managing OAuth Redirect URIs using dynamically created subdomains for unique branches

In my next.js project that utilizes next-auth and is being deployed on Vercel, I am facing an issue with OAuth authentication through Google. While I have successfully set up the OAuth provider for localhost and production environments, Vercel also gener ...

A step-by-step guide on obtaining a reference to the Nextjs server

Incorporating ws (web socket) into my Nextjs application is something I'm working on. Instead of setting up a new server, my goal is to hand over the existing server object to initialize ws: const { Server } = require('ws'); wss = new Serve ...