Next.js 13调用.NET Core 7 API出现fetch failed错误求助
解决Next.js 13调用.NET Core 7 API出现fetch failed的问题
你遇到的fetch failed错误,核心原因是Next.js 13的异步组件默认是服务器组件,fetch请求在服务器端发起,和浏览器/Postman的请求环境完全不同——CORS是浏览器端的安全机制,所以之前配置的CORS在这里不起作用。下面是几个针对性的解决方案:
方案1:禁用开发环境下的HTTPS证书验证
你的.NET API使用HTTPS的localhost地址,自签名证书会被Next.js内置的HTTP客户端undici拒绝,导致请求失败。可以在fetch中添加证书跳过选项(仅限开发环境使用,生产环境务必删除):
import Image from 'next/image' import { Agent } from 'undici' async function getChamps () { const fetchOptions = {} // 仅开发环境关闭证书验证 if (process.env.NODE_ENV === 'development') { fetchOptions.agent = new Agent({ connect: { rejectUnauthorized: false } }) } const res = await fetch('https://localhost:7046/api/Champion', fetchOptions) if (!res.ok) { throw new Error('Failed to fetch data') } return res.json() } export default async function ListOfChampions () { const champions = await getChamps() return ( <ul> {champions.map(champ => ( <li key={champ.champion_id}> <Image src={champ.image} alt={champ.name} width={100} height={100} /> <p>{champ.name}</p> </li> ))} </ul> ) }
方案2:使用Next.js代理转发请求
通过Next.js的rewrite配置,把前端的/api请求代理到.NET API,既能绕开证书问题,也不需要依赖CORS配置:
- 在项目根目录创建/修改
next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { async rewrites() { return [ { source: '/api/:path*', destination: 'https://localhost:7046/api/:path*' } ] } } module.exports = nextConfig
- 修改fetch的URL为相对路径:
async function getChamps () { // 相对路径会被Next.js自动代理到.NET API const res = await fetch('/api/Champion') if (!res.ok) { throw new Error('Failed to fetch data') } return res.json() }
方案3:修改.NET API的绑定地址
如果Next.js和.NET API运行在不同网络环境(比如容器),localhost可能无法互通。修改.NET项目的launchSettings.json,把API绑定到0.0.0.0:
{ "profiles": { "YourApiProject": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "https://0.0.0.0:7046;http://0.0.0.0:5046", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
重启.NET API后,Next.js的服务器端fetch就能正常访问到API了。
内容的提问来源于stack exchange,提问作者Martín Cárdenas
相关产品推荐
相关产品推荐

