gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:27:33 35 4
gpt4 key购买 nike

我目前正在尝试创建一个中间件,通过使用 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据此 question
我的代码想要
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

}

关于javascript - Next.js v12 中间件不适用于 node-fetch 和 axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70992541/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com