Spring框架和nextjs axios数据传输问题

问题描述 投票:0回答:1

我想在项目中使用 Spring 和 Nextjs。

我曾经用 Spring 和 React 做项目。

Nextjs 13 版本提供了 api/route 结构,因此与常规 React 框架相比非常有趣。

当我使用 React 时,我使用了容器 - 呈现模式并在容器组件中编写 axios 代码。

实际上在 Nextjs 中,我可以那样使用。但是我想通过 Next 的 api/route 结构来操作数据。

出于安全原因,使用 Next 的结构似乎更有益。

问题是我无法传递序列以下的数据。

Spring -> api/route -> pageComponent

我可以传递序列下面的数据。

Spring -> pageComponent

api/route -> pageComponent

以下是我的代码。

--- 春天

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

}

--- 下一步

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

解决 Spring 和 NextJS 数据传输问题。

spring spring-boot next.js next
1个回答
0
投票

似乎 app/api fetch 可以被内部的同一个 node.js 前端服务器使用。 这就是为什么它没有重新运行任何后端数据,所以我使用客户端 axios 代码来调用后端数据。

© www.soinside.com 2019 - 2024. All rights reserved.