[英]how to correctly fetch data in getServerSideProps
Using Next.js I came across this problem:使用 Next.js 我遇到了这个问题:
As soon as I reach pages/users , I got this error一到达pages/users ,我就收到了这个错误
./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0
Module not found: Can't resolve 'dns'
Import trace for requested module:
./node_modules/mongodb/lib/index.js
./models/user/addedUserModel.js
./pages/api/users/index.js
./pages/users.js
https://nextjs.org/docs/messages/module-not-found
I'm trying to fetch all the users from getServerSideProps , inside pages/users我正在尝试从getServerSideProps获取所有用户,内部页面/用户
import { Layout, Meta, Card, Button } from "../components/ui";
import {useAxios} from "../utils/hooks/requests/useAxios";
import {useNotifications} from "../context/notifications/notifications_context";
const Users = ({users}) => {
const {handleDeleteRequest} = useAxios("api/users");
const {notification} = useNotifications()
const removeUser = async (_id) => {
await handleDeleteRequest(_id)
}
return (
<>
<Layout>
<Meta title="Users"/>
<Card>
{users.addedUsers.map(user => <div className="flex border-b items-center justify-between"
key={user._id}>
<div className="p-2">
<h2>{user.name}</h2>
</div>
<div>
<Button onClick={() => removeUser(user._id)} className="bg-red-500">Delete</Button>
</div>
</div>)}
</Card>
</Layout>
{notification.text ? <div
className={`${notification.isError ? 'bg-red-500 ' : 'bg-green-500 '} absolute top-0 left-0 w-full p-2 flex items-center justify-center text-white font-semibold`}>
<p>{notification.text}</p>
</div> : null}
</>
)
}
export default Users;
export async function getServerSideProps() {
const res = await fetch("http://localhost:3000/api/users")
const users = await res.json()
return {
props: { users }
}
}
The folder structure of the api endpoint is as follows -> api/users/index.js api端点的文件夹结构如下-> api/users/index.js
Under the pages/users folder I've got an [id].js file to delete a single user.在pages/users文件夹下,我有一个[id].js文件来删除单个用户。
So the problem lives in the getServerSideProps function or there's something else I'm missing to get rid of this dns
error?所以问题出在 getServerSideProps function 或者我还缺少其他东西来摆脱这个
dns
错误?
Also, I want to re-fetch all the users after removing one of them, to have a fresh users list without refreshing the page.另外,我想在删除其中一个用户后重新获取所有用户,以便在不刷新页面的情况下获得新的用户列表。 Isn't getServerSideProps useful to do this job??
getServerSideProps对完成这项工作没有用吗?
getServerSideProps
allows you to fetch data on the server-side before rendering the page. getServerSideProps
允许您在呈现页面之前在服务器端获取数据。 This means that when a user visits the pages/users
page, the data will be fetched from the server and returned as part of the props object to the component这意味着当用户访问
pages/users
页面时,数据将从服务器获取并作为 props object 的一部分返回给组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.