我目前正在尝试创建一个中间件,通过使用 Axios 获取外部端点来获取用户数据。 axios 也不能与中间件一起使用。这是我使用 node-fetch 时的错误:
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_modules\axios\lib\core\dispatchRequest.js (53:0) @ dispatchRequest
TypeError: adapter is not a function
我必须根据这个问题安装axios-fetch-adapter
我的代码想要
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
}