返回

从零到一,基于React,NodeJs,MySQL,开发属于你的掘金评论模块

前端

前言

评论模块是现代Web应用程序中必不可少的功能之一,它允许用户对文章、产品或服务发表自己的看法和见解,从而增强用户参与度和互动性。掘金作为国内知名的技术社区,其评论模块设计简洁、功能强大,值得我们学习和借鉴。

本教程将带领你从零开始开发一个类似于掘金的评论模块,涵盖了整个评论模块的开发过程,包括:

  • React前端: 使用React构建评论模块的前端界面,包括评论列表、评论表单等组件。
  • Node.js后端: 使用Node.js构建评论模块的后端服务,包括评论数据的存储、检索和管理等功能。
  • MySQL数据库: 使用MySQL作为评论模块的数据存储后端,负责存储评论数据。

技术选型

本教程中,我们将使用以下技术栈:

  • React: 一个用于构建用户界面的JavaScript库。
  • Node.js: 一个基于JavaScript的运行时环境,用于构建Web应用程序的后端服务。
  • MySQL: 一个流行的关系型数据库管理系统,用于存储评论数据。

开发步骤

1. 创建React项目

首先,我们需要创建一个React项目。你可以使用以下命令创建一个新的React项目:

npx create-react-app my-comment-module

2. 安装依赖项

接下来,我们需要安装必要的依赖项。使用以下命令安装React、Node.js和MySQL的依赖项:

npm install react react-dom nodemon mysql2

3. 构建React前端

src目录下创建CommentList.jsCommentForm.js两个文件,分别用于构建评论列表和评论表单组件。

CommentList.js

import React, { useState, useEffect } from "react";
import Comment from "./Comment";

const CommentList = () => {
  const [comments, setComments] = useState([]);

  useEffect(() => {
    fetch("/api/comments")
      .then(res => res.json())
      .then(data => setComments(data))
      .catch(err => console.error(err));
  }, []);

  return (
    <ul>
      {comments.map(comment => <Comment key={comment.id} comment={comment} />)}
    </ul>
  );
};

export default CommentList;

CommentForm.js

import React, { useState } from "react";

const CommentForm = () => {
  const [author, setAuthor] = useState("");
  const [content, setContent] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    const comment = {
      author: author,
      content: content
    };

    fetch("/api/comments", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(comment)
    })
      .then(res => res.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={author} onChange={e => setAuthor(e.target.value)} />
      <textarea value={content} onChange={e => setContent(e.target.value)} />
      <button type="submit">提交</button>
    </form>
  );
};

export default CommentForm;

4. 构建Node.js后端

在项目根目录下创建server.js文件,用于构建Node.js后端服务。

const express = require("express");
const mysql = require("mysql2");

const app = express();
app.use(express.json());

const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
  database: "my_comment_module"
});

app.get("/api/comments", (req, res) => {
  connection.query("SELECT * FROM comments", (err, results) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.json(results);
    }
  });
});

app.post("/api/comments", (req, res) => {
  const comment = req.body;
  connection.query("INSERT INTO comments SET ?", comment, (err, result) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.json(result);