如何在next 13的API中的route.ts文件中使用app router读取请求主体和查询参数?

huangapple go评论62阅读模式
英文:

How to read request body and query params in next 13's API with app router in route.ts file?

问题

未在此处找到任何解决方案: https://nextjs.org/docs/app/api-reference/file-conventions/route.

英文:

Did not found any solution here: https://nextjs.org/docs/app/api-reference/file-conventions/route.

答案1

得分: 11

在NextJS 13中,在app/api/route.js中,您可以使用URL类来读取参数。

export async function GET(req){
    const {searchParams} = new URL(req.url);
    const param = searchParams.get("/*Your param key here*/");
    console.log(param)
}

要获取req的请求体

export async function POST(req){
    const body = await req.json()
    console.log(body)
}
英文:

In NextJS 13, in app/api/route.js you can use URL class to read the params

export async function GET(req){
    const {searchParams} = new URL(req.url);
    const param = searchParams.get("/*Your param key here*/");
    console.log(param)
}

To get req body

export async function POST(req){
    const body = await req.json()
    console.log(body)
}

答案2

得分: 8

The dynamic route parameter is in the second argument.

/api/something/[id]/route.ts

export async function GET(req, { params }) {
  const id = params.id;
}
英文:

For anyone looking to grab the dynamic route parameter like I was, it's in the second argument.

/api/something/[id]/route.ts

export async function GET(req, { params }) {
  const id = params.id;
}

答案3

得分: 1

我现在相信最好的方法就是简单地使用

req.nextUrl.searchParams


export const GET = async (req) => {
// 请求体
const requestBody = await request.json();

// 搜索参数
const searchParams = req.nextUrl.searchParams;
const foo = searchParams.get('foo');

}


如果你检查`NextURL`类型定义,里面有很多好东西。
英文:

The best way I believe now is to simply use

req.nextUrl.searchParams
export const GET = async (req) => {
    // Req Body
    const requestBody = await request.json();


    // Search Params
    const searchParams = req.nextUrl.searchParams;
    const foo = searchParams.get('foo');
}

If you check the NextURL type def there is a lot of good stuff in there.

答案4

得分: 0

在NextJS 13中,使用app目录中的route.ts文件规范,我们可以使用以下代码读取查询参数和请求体:

import url from "URL";

export async function POST(request: Request) {

  const requestBody = await request.json(); // 读取请求数据

  const queryParams = url.parse(request.url, true).query;  // 读取查询参数

  // 返回查询参数和请求体
  return NextResponse.json({
    requestBody,
    queryParams,
  });

}
英文:

In NextJS 13, with route.ts File Conventions in app dir, we can read query params and request's body with this:

<!-- language: lang-js -->

import url from &quot;URL&quot;;

export async function POST(request: Request) {

  const requestBody = await request.json(); // To read request data

  const queryParams = url.parse(request.url, true).query;  // To read query params

  // Returning the query params &amp; body
  return NextResponse.json({
    requestBody,
    queryParams,
  });

}

<!-- end snippet -->

答案5

得分: 0

这是声明类 NextURL。

所以我们可以使用 req.nextUrl.searchParams.get('xyz') XD。

英文:

It's declare class NextURL.

So we can use req.nextUrl.searchParams.get(&#39;xyz&#39;) XD.

答案6

得分: 0

以下是如何读取Nextjs 13应用程序目录和Typescript的请求正文和查询参数的方法:

import { NextRequest, NextResponse } from 'next/server'

// 在app/api/route.ts内
// 这将创建端点GET http://localhost:3000/api

// 像这样测试http://localhost:3000/api?name=Meera

export async function GET(request: NextRequest) {

    const { searchParams } = new URL(request.url);
    const name = searchParams.get("name");

    return NextResponse.json({ name })
}

// 这将创建端点POST http://localhost:3000/api

export async function POST(request: NextRequest) {

    try {
        const json = await request.json();

        return NextResponse.json(json)

    } catch (e) {
        console.log(e);
        return new Response(null, { status: 400, statusText: "Bad Request" });
    }
}
英文:

Here is how you can read the request body and query parameters for the Nextjs 13 app directory and Typescript:

import { NextRequest, NextResponse } from &#39;next/server&#39;


// Inside app/api/route.ts
// This will create end point GET http://localhost:3000/api

// Test this like http://localhost:3000/api?name=Meera

export async function GET(request: NextRequest) {

    const {searchParams} = new URL(request.url);
    const name = searchParams.get(&quot;name&quot;);

    return NextResponse.json({name})
}

// This will create end point POST http://localhost:3000/api

export async function POST(request: NextRequest) { 

    try {
        const json = await request.json();

        
        return NextResponse.json(json)
    
    
      } catch (e) {
        console.log(e);
        return new Response(null, { status: 400, statusText: &quot;Bad Request&quot; });
      }


}

huangapple
  • 本文由 发表于 2023年5月14日 18:05:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246886.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定