【问题标题】:Next.js v12 middleware does not work with node-fetch and axiosNext.js v12 中间件不适用于 node-fetch 和 axios
【发布时间】:2022-02-12 02:46:46
【问题描述】:

我目前正在尝试创建一个中间件,该中间件将通过使用 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


【解决方案1】:

在我的情况下,我在中间件中使用 axios,并收到以下错误

error - node_modules\axios\lib\core\dispatchRequest.js (53:0) @ dispatchRequest
TypeError: adapter is not a function

我不得不根据这个question安装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

}

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2021-06-30
    • 2018-06-06
    • 2020-11-19
    • 2019-05-29
    • 2022-10-05
    相关资源
    最近更新 更多