使用 API 在 NextJs 中执行服务器操作以进行脚本或负载测试

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

我们的应用程序是基于 NextJs 构建的,如果我们必须通过调用 API 来执行负载测试,我们将如何使用 API 本身调用服务器操作?

调用服务器操作需要在请求标头中添加一个

next-action
参数,如何生成一个参数?如果没有这个参数,将会重定向到一个页面。

下面是查看下一步操作标题的图片。

enter image description here

服务器操作实际上调用

POST
方法 API,其端点与页面相同。

当然,我们可以从浏览器控制台复制

next-action
标头,但我们不能每次都这样做。 此外,每当生成新版本时,它都会生成不同的哈希值。因此,使用 API 进行负载测试或任何脚本编写目的进行复制是非常困难的。

有人知道如何实现这一目标吗?

我尝试询问 AI,但它给出了错误的答案,在

next
模块中给出了随机路径,因此引发了错误。

javascript next.js server-action
1个回答
0
投票

您可以创建一个中间件,将所需的

next-action
标头添加到来自负载测试工具的请求中。这需要您在中间件可访问的地方生成并存储正确的哈希值。

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  // Check if the request is coming from your load testing tool
  if (request.headers.get('X-Load-Test') === 'true') {
    const response = NextResponse.next()
    // Add the next-action header
    // You'll need to generate and store this hash somewhere
    response.headers.set('next-action', 'your-generated-hash')
    return response
  }
  return NextResponse.next()
}

export const config = {
  matcher: '/api/:path*',
}

我找到了这个解决方案希望它有效。

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