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

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

我目前正在尝试创建一个中间件,通过使用 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();
};
javascript node.js typescript axios next.js
2个回答
6
投票

在我的例子中,我在中间件中使用 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

}

0
投票

切换到xior将解决这个问题。因为 Next.js middleware.js 运行在

edge runtime
中,只支持
fetch
,不支持 Nodejs
http
模块。

这是 xior 功能

🔥 使用获取

🫡类似的axios API:axios.create / axios.interceptors / .get/post/put/patch/delete/head/options

🤙 支持超时和取消请求

🥷插件支持:错误重试、缓存、节流,轻松创建自定义插件

🚀 轻量级(〜6KB,Gzip〜2.6KB)

👊 经过单元测试和强类型 💪

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