簡體   English   中英

Next.js v12 中間件不適用於 node-fetch 和 axios

[英]Next.js v12 middleware does not work with node-fetch and axios

我目前正在嘗試創建一個中間件,該中間件將通過使用 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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM