学习笔记-WEB-全栈框架Nextjs之FetchData

Fake API

https://jsonplaceholder.typicode.com/posts

基本使用

控制行为

// 默认
fetch("url", {cache: "force-cache"});
// 不缓存
fetch("url", {cache: "no-store"});
// 定时刷新 s
fetch("url", {revalidate:3600});

不使用API

基本使用

// src/lib/data.js

// TEMPORARY DATA
// 后面可以用数据库链接取代
const users = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
];

const posts = [
  { id: 1, title: "Post 1", body: "......", userId: 1 },
  { id: 2, title: "Post 2", body: "......", userId: 1 },
  { id: 3, title: "Post 3", body: "......", userId: 2 },
  { id: 4, title: "Post 4", body: "......", userId: 2 },
];

MongoDB

安装mongodb或使用云

在.env.xxx中配置mongodb环境变量

在nextjs项目中安装mongodb或mongoose

创建数据库链接函数
// /lib/utils.js

import mongoose from "mongoose"

// 防止重复链接
const connection = {};

export const connectToDb = async () => {
  try {
    if(connection.isConnected) {
      console.log("Using existing connection");
      return;
    }
    const db = await mongoose.connect(process.env.MONGO);
    connection.isConnected = db.connections[0].readyState;
  } catch (error) {
    console.log(error);
    throw new Error(error);
  }
};
创建模型文件
// /lib/model.js

import mongoose from "mongoose";

const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
      required: true, // 必须
      unique: true,   // 唯一
      min: 3,         // 长度约束
      max: 20,
    },
    email: {
      type: String,
      required: true,
      unique: true,
      max: 50,
    },
    password: {
      type: String,
    },
    img: {
      type: String,
    },
    isAdmin: {
      type: Boolean,
      default: false, // 默认值
    },
  },
  { timestamps: true }// 自动添加时间戳
                      // 字段为 createdAt: yyyy-mm-ddThh:mm:ss.mmm+00:00
);

const postSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    desc: {
      type: String,
      required: true,
    },
    img: {
      type: String,
    },
    userId: {
      type: String,
      required: true,
    },
    slug: {
      type: String,
      required: true,
      unique: true,
    },
  },
  { timestamps: true }
);

// 数据库中如果有model则使用数据库中的
export const User = mongoose.models?.User || mongoose.model("User", userSchema);
export const Post = mongoose.models?.Post || mongoose.model("Post", postSchema);

注意mongodb数据库中会默认添加_id字段,这也是findbyid所检索的字段

使用数据库

find/findOne/findById/findByIdAndDelete

noStore用于避免缓存

// data.js

import { Post, User } from "./models";
import { connectToDb } from "./utils";
import { unstable_noStore as noStore } from "next/cache";

// TEMPORARY DATA
// const users = [
//   { id: 1, name: "John" },
//   { id: 2, name: "Jane" },
// ];

// const posts = [
//   { id: 1, title: "Post 1", body: "......", userId: 1 },
//   { id: 2, title: "Post 2", body: "......", userId: 1 },
//   { id: 3, title: "Post 3", body: "......", userId: 2 },
//   { id: 4, title: "Post 4", body: "......", userId: 2 },
// ];

export const getPosts = async () => {
  try {
    connectToDb();
    const posts = await Post.find();
    return posts;
  } catch (err) {
    console.log(err);
    throw new Error("Failed to fetch posts!");
  }
};

export const getPost = async (slug) => {
  try {
    connectToDb();
    const post = await Post.findOne({ slug });
    return post;
  } catch (err) {
    console.log(err);
    throw new Error("Failed to fetch post!");
  }
};

export const getUser = async (id) => {
  noStore();
  try {
    connectToDb();
    const user = await User.findById(id);
    return user;
  } catch (err) {
    console.log(err);
    throw new Error("Failed to fetch user!");
  }
};

export const getUsers = async () => {
  try {
    connectToDb();
    const users = await User.find();
    return users;
  } catch (err) {
    console.log(err);
    throw new Error("Failed to fetch users!");
  }
};

其他说明

通常fetch同一个接口或使用数据库获取同一数据多次不会重复执行。

Vue.js 是一个流行的前端JavaScript框架,用于构建用户界面和单页应用程序。它由尤雨溪(Evan You)创建,并且受到AngularJS和ReactJS的启发。Vue.js的核心库只关注视图层,易于上手,同时它还能够通过插件的形式提供更广泛的解决方案。 `ref` 是 Vue 中的一个属性,它是一个特殊的属性,用于给元素或子组件注册引用信息。引用信息将会被存储在父组件的 `$refs` 对象上。如果是在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果是在子组件上使用,则引用指向的是组件实例。 `fetch-data` 不是 Vue.js 的官方属性或方法,但通常指的是在 Vue 应用中从服务器获取数据的过程。在 Vue 中,可以通过多种方式实现数据的获取,例如使用 `axios`、`fetch` 等HTTP客户端库,或者使用 Vue 的 `created` 钩子函数或者 `mounted` 钩子函数中来获取数据。 以下是一个简单的例子,展示了如何在 Vue 组件中使用 `fetch` 方法来获取数据,并将数据保存到组件的 `data` 属性中: ```javascript <template> <div> <h1>{{ title }}</h1> </div> </template> <script> export default { data() { return { title: null }; }, created() { this.fetchData(); }, methods: { fetchData() { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { this.title = data.title; }) .catch(error => console.error('Error:', error)); } } }; </script> ``` 在上面的例子中,`fetchData` 方法会在组件被创建后调用,它使用 `fetch` API 从指定的 URL 获取数据,并更新组件的 `title` 数据属性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值