遇到问题在获取服务器组件数据。

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

Having trouble fetching data on sever components

问题

我在尝试访问服务器组件上的路径名时遇到了问题,因为我需要获取路径名上的表单的ID,并且我希望它是一个服务器组件。有时代码可用,有时不可用。我在我的后端服务器上进行调试,当代码不起作用时我没有收到ID。这是我的服务器组件上的代码:

导入"./style.css";
导入axios from "axios";
导入FormSection from "./FormSection";
导入{ headers } from "next/headers";

const fetchForm = async (pathname) => {
  const id = pathname.split("/").pop();
  const res = await axios({
    method: "POST",
    url: `${process.env.NEXT_PUBLIC_FORM_ROUTES_INT_URL}/api`,
    data: {
      query: `...`,
      variables: {
        getFormId: id,
      },
    },
  });
  // 验证
  如果(res.data.errors) {
    抛出新错误(res.data.errors[0].message);
  }
  // 逻辑以重定向到创建的表单ID
  返回res.data.data.getFormForSubmission;
};

默认导出异步函数CustomerFormPage() {
  const fullUrl = headers().get("referer") || "";
  const form = await fetchForm(fullUrl);
  返回(
    <div className="h-100 row m-0" style={{ maxWidth: "100vw" }}>
      <div className="row mx-auto my-auto card-container col-sm-12 col-md-10 col-lg-10 col-xl-6">
        <div className="col-md-6 col-sm-12 p-5">
          <h3>{form.title}</h3>
          <p>{form.description}</p>
        </div>
        <div className="col-md-6 col-sm-12 p-5">
          <FormSection fields={form.inputs} />
        </div>
        <div className="poweredBy">
          <p>
            由<a href="#">Form Lite</a>提供支持
          </p>
        </div>
      </div>
    </div>
  );
}

有时我们将friendlyId发送到服务器,有时没有,所以我遇到了表单未找到的错误。有人知道如何解决这个问题吗?谢谢

英文:

Im having an issue trying to access the pathname on a server component, because I need to get the ID of the form that its on the pathname, and I want it to be a server component.
Sometimes the code works and sometimes doesn't. I'm debugging on my back end server and Im not receiving the ID when the code doesnt work.
This is my code on the server component:

import &quot;./style.css&quot;;
import axios from &quot;axios&quot;;
import FormSection from &quot;./FormSection&quot;;
import { headers } from &quot;next/headers&quot;;

const fetchForm = async (pathname) =&gt; {
  const id = pathname.split(&quot;/&quot;).pop();
  const res = await axios({
    method: &quot;POST&quot;,
    url: `${process.env.NEXT_PUBLIC_FORM_ROUTES_INT_URL}/api`,
    data: {
      query: `...`,
      variables: {
        getFormId: id,
      },
    },
  });
  // Validation
  if (res.data.errors) {
    throw new Error(res.data.errors[0].message);
  }
  // Logic para redirecionar al id del form creado
  return res.data.data.getFormForSubmission;
};

export default async function CustomerFormPage() {
  const fullUrl = headers().get(&quot;referer&quot;) || &quot;&quot;;
  const form = await fetchForm(fullUrl);
  return (
    &lt;div className=&quot;h-100 row m-0&quot; style={{ maxWidth: &quot;100vw&quot; }}&gt;
      &lt;div className=&quot;row mx-auto my-auto card-container col-sm-12 col-md-10 col-lg-10 col-xl-6&quot;&gt;
        &lt;div className=&quot;col-md-6 col-sm-12 p-5&quot;&gt;
          &lt;h3&gt;{form.title}&lt;/h3&gt;
          &lt;p&gt;{form.description}&lt;/p&gt;
        &lt;/div&gt;
        &lt;div className=&quot;col-md-6 col-sm-12 p-5&quot;&gt;
          &lt;FormSection fields={form.inputs} /&gt;
        &lt;/div&gt;
        &lt;div className=&quot;poweredBy&quot;&gt;
          &lt;p&gt;
            Powered by &lt;a href=&quot;#&quot;&gt;Form Lite&lt;/a&gt;
          &lt;/p&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
}

Sometimes we are sending the friendlyId to the server and sometimes not so Im having an error form not found.

Someone knows how to fix this?
Thanks

答案1

得分: 0

我修复了创建中间件并将路径存储在cookie中的问题:

middleware.js:

import { NextResponse, NextRequest } from "next/server";
import { getToken } from 'next-auth/jwt';

export async function middleware(req) {
  const { pathname } = req.nextUrl;
  const token = await getToken({ req, secret: process.env.JWT_SECRET });

  if (!token && pathname !== "/login" && pathname !== "/register" && !pathname.startsWith('/fms/')) {
    return NextResponse.redirect(new URL('/login', req.url))
  }

  if (req.nextUrl.pathname.startsWith('/fms/')) {
    const requestHeaders = new Headers(req.headers);
    requestHeaders.set('x-url', req.url);
    return NextResponse.next({
      request: {
        // Apply new request headers
        headers: requestHeaders,
      }
    });
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/forms/:path*", "/", "/help", "/settings/:path*", "/fms/:path*"],
};

然后,在服务器组件中获取路径:

import { headers } from "next/headers";
const headersList = headers();
const headerUrl = headersList.get('x-url') || '';

希望我的回答对某人有帮助。

英文:

I fixed creating a middleware and storing the path on a cookie:

middleware.js:

import { NextResponse, NextRequest } from &quot;next/server&quot;;
import { getToken } from &#39;next-auth/jwt&#39;;

export async function middleware(req) {
  const { pathname } = req.nextUrl;
  const token = await getToken({ req, secret: process.env.JWT_SECRET });

  if (!token &amp;&amp; pathname != &quot;/login&quot; &amp;&amp; !pathname != &quot;/register&quot; &amp;&amp; !pathname.startsWith(&#39;/fms/&#39;)) {
    return NextResponse.redirect(new URL(&#39;/login&#39;, req.url))
  }

  if (req.nextUrl.pathname.startsWith(&#39;/fms/&#39;)) {
    const requestHeaders = new Headers(req.headers);
    requestHeaders.set(&#39;x-url&#39;, req.url);
    return NextResponse.next({
      request: {
        // Apply new request headers
        headers: requestHeaders,
      }
    });
  }

  return NextResponse.next();
}

export const config = {
  matcher: [&quot;/forms/:path*&quot;, &quot;/&quot;, &quot;/help&quot;, &quot;/settings/:path*&quot;, &quot;/fms/:path*&quot;],
};

And then to get the path on the server component:

import { headers } from &quot;next/headers&quot;;
const headersList = headers();
const headerUrl = headersList.get(&quot;x-url&quot;) || &quot;&quot;;

Hope I help someone with my answer.

huangapple
  • 本文由 发表于 2023年6月22日 00:12:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525261.html
匿名

发表评论

匿名网友

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

确定