无法通过NextJS在HTTP post请求中访问正文。

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

Cannot access body in a HTTP post through NextJS

问题

我认为我正在忽略一些显而易见的东西,但我需要另一个头脑来帮助我解决这个问题。

我的目标是访问 POST 请求的正文,就像在下面这个页面中所示。
https://nextjs.org/docs/pages/building-your-application/data-fetching/building-forms

// 根文件夹中的 page.js 文件
//===========================

import Image from 'next/image'
import styles from './page.module.css'

export default function Home() {
  return (
    <main className={styles.main}>
      <div className={styles.description}>
        <p>
          <form action="/route" method="post">
            <label for="first">First name:</label>
            <input type="text" id="first" name="first"/><br/><br/>
            <label for="last">Last name:</label>
            <input type="text" id="last" name="last"/><br/><br/>
            <input type="submit" value="Submit"/>
          </form>
        </p>
      </div>
    </main>
  )
}
// /response/response.js
// ===========================
import { NextResponse } from 'next/server';
 
export async function GET(req, res) {
  console.log("====GET====");
  console.log(req.body);
  return NextResponse.json("get");
}

export async function POST(req) {
  const body = req.body;
  console.log(body);
  return NextResponse.json("post");
}

我填写表单,浏览器正确路由到“post”响应,当我提交时,“get”响应列出。但是,在服务器端,响应正文被记录为:

ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

当我阅读链接以及关于 nextjs 和处理 POST 请求的所有其他文档时,正文的内容就像它是一个对象,而不是可读流。此外,我找不到 nextjs 网站上显示如何解码可读流的任何内容,这似乎对于常见任务来说有点复杂。

我相当确定我忽略了一些平凡的细节,比如放错了小数点,但我需要帮助找到它。

非常感谢各位!

Chris Roode

英文:

I think I'm missing something obvious, but I need another head to get me unstuck.

My objective: get access to the body of a POST request as shown in this page from nextjs.
https://nextjs.org/docs/pages/building-your-application/data-fetching/building-forms

// root folder page.js file
//===========================

import Image from &#39;next/image&#39;
import styles from &#39;./page.module.css&#39;

export default function Home() {
  return (
 &lt;main className={styles.main}&gt;
 	&lt;div className={styles.description}&gt;
		&lt;p&gt;
			&lt;form action=&quot;/route&quot; method=&quot;post&quot;&gt;
				&lt;label for=&quot;first&quot;&gt;First name:&lt;/label&gt;
				&lt;input type=&quot;text&quot; id=&quot;first&quot; name=&quot;first&quot;/&gt;&lt;br/&gt;&lt;br/&gt;
				&lt;label for=&quot;last&quot;&gt;Last name:&lt;/label&gt;
				&lt;input type=&quot;text&quot; id=&quot;last&quot; name=&quot;last&quot;/&gt;&lt;br/&gt;&lt;br/&gt;
				&lt;input type=&quot;submit&quot; value=&quot;Submit&quot;/&gt;
			&lt;/form&gt;
        &lt;/p&gt;
    &lt;/div&gt;
&lt;/main&gt;
  )
}
// /response/response.js
// ===========================
import { NextResponse } from &#39;next/server&#39;;
 
export async function GET(req, res) {
	console.log(&quot;====GET====&quot;);
	console.log(req.body);
	return NextResponse.json(&quot;get&quot;);
}

export async function POST(req) {
	const body = req.body;
	console.log(body);
  return NextResponse.json(&quot;post&quot;);
}

I fill out the form, and the browser routes correctly to the 'post' response, and the 'get' response lists when I submit. However, on the server side, the response body is logged:

ReadableStream { locked: false, state: &#39;readable&#39;, supportsBYOB: false }

When I read the link, and all other documentation on nextjs and handling POST requests, the contents of the post as if it's an object, and not a readable stream. Furthermore, I can't find anything on nextjs's website showing how to decode the readable stream, which seems a bit extensive of a solution for a common task.

I'm pretty sure I'm missing some mundane detail, like putting a decimal point in the wrong place, but I need help finding it.

Thanks a bunch peoples!

Chris Roode

答案1

得分: 2

由于您正在以application/x-www-form-urlencoded格式提交表单,您可以按以下方式访问表单数据:

export async function POST(req) {
  const data = await req.formData();
  const firstName = data.get("first");
  const lastName = data.get("last");
  console.log({ firstName, lastName });
  return NextResponse.json("post");
}
英文:

Since you are submitting your form as application/x-www-form-urlencoded, you can access your form data as follows:

export async function POST(req) {
  const data = await req.formData();
  const firstName = data.get(&quot;first&quot;);
  const lastName = data.get(&quot;last&quot;);
  console.log({ firstName, lastName });
  return NextResponse.json(&quot;post&quot;);
}

huangapple
  • 本文由 发表于 2023年5月25日 20:52:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332480.html
匿名

发表评论

匿名网友

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

确定