1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React / Next.js】Error [TypeError]: res.status is not a function at handler の解決方法について

Posted at

はじめに

udemyのNext.jsハンズオンでデータベースから情報を取得する実装中に下記のエラーに遭遇しましたので、こちらの解決方法について記事にします。
前提条件として、ハンズオンではSupabaseによるAPIでのデータを取得しておりますが、今回CloudflareのD1を利用しております。

エラー内容

Error [TypeError]: res.status is not a function
at handler (src/pages/api/index.ts:19:13)

Edge Runtimeはres.statusは使えないということのようでした。

修正前コード

.index.ts
import { getRequestContext } from "@cloudflare/next-on-pages";
import { NextApiRequest, NextApiResponse } from "next";

export const runtime = 'edge';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const env = getRequestContext().env;

  const result = await env.DB.prepare("SELECT * FROM posts").all();
  console.log('result', result);

  if(!result) {
    return res.status(500).json({ error: "Server Error" });
  }

  return res.status(200).json(result.results);
}

【修正後】

.index.ts
import { getRequestContext } from "@cloudflare/next-on-pages";

export const runtime = 'edge';

export default async function handler() {

  const env = getRequestContext().env;
  const result = await env.DB.prepare("SELECT * FROM posts").all();

  console.log('result', result);

  if(!result) {
    return new Response(JSON.stringify({ error: "Server Error" }))
  };
  return new Response(JSON.stringify(result.results));

}

参考

おわりに

これでデータが取得できるようになりました。


JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?