Next.js v12中间件不适用于node fetch和axios



我目前正试图创建一个中间件,通过Axios获取外部端点来处理用户数据。Axios也不适用于中间件。以下是我在使用节点提取时的错误:

Module build failed: UnhandledSchemeError: Reading from "node:buffer" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.

知道为什么会发生这种事吗?

这是我的代码:

import fetch from "node-fetch"
import { getSession } from "next-auth/react";
import { NextMiddleware, NextResponse } from "next/server";
export const middleware: NextMiddleware = async (req, ev) => {
const session = await getSession() as any;
const user = await fetch("some-url", {
headers: {
Authorization: `Bearer ${session?.user?.someproperty}`,
},
});
if (user.statusCode !== 200) return NextResponse.redirect(req.url);
else return NextResponse.next();
};

在我的案例中,我在中间件中使用axios,并得到以下错误

error - node_modulesaxioslibcoredispatchRequest.js (53:0) @ dispatchRequest
TypeError: adapter is not a function

我不得不根据这个问题安装axios获取适配器

我的代码想要

import type { NextFetchEvent, NextRequest } from 'next/server'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axios from 'axios'
export async function middleware(req: NextRequest, ev: NextFetchEvent) {
const axiosInstance = axios.create({
adapter: fetchAdapter
})
const data = await axiosInstance.get('/whatever-url')
// the rest of the code
}

或者,如果您已经有一个带有自定义选项的预配置实例

import type { NextFetchEvent, NextRequest } from 'next/server'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axiosInstance from './the-path-of-your-instance'
export async function middleware(req: NextRequest, ev: NextFetchEvent) {
axiosInstance.defaults.adapter = fetchAdapter
const data = await axiosInstance.get('/whatever-url')
// the rest of the code
}

最新更新