英文:
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 "./style.css";
import axios from "axios";
import FormSection from "./FormSection";
import { 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,
},
},
});
// 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("referer") || "";
const form = await fetchForm(fullUrl);
return (
<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>
Powered by <a href="#">Form Lite</a>
</p>
</div>
</div>
</div>
);
}
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 "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*"],
};
And then to get the path on the server component:
import { headers } from "next/headers";
const headersList = headers();
const headerUrl = headersList.get("x-url") || "";
Hope I help someone with my answer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论