Home > Web Front-end > JS Tutorial > body text

How to build a simple social media platform using Node.js

PHPz
Release: 2023-11-08 11:05:07
Original
762 people have browsed it

How to build a simple social media platform using Node.js

Social media platforms have become one of the most popular and trending applications in today's era, and Node.js is a JavaScript runtime widely used in web development that is extremely efficient The flexibility and adaptability make using Node.js to build a social media platform a good choice. In this article, we will learn how to build a simple social media platform using Node.js.

  1. Installing Node.js

First, make sure Node.js is installed on your computer. You can check whether Node.js is installed by running the following command:

node -v
Copy after login

If you have Node.js installed, it will output the version number you currently have enabled. If you have not installed Node.js, please install the latest version of Node.js based on your computer type, operating system, and operating environment.

  1. Initialize the project

We start creating our project. First, create a new directory on your computer using the following command:

mkdir social-media-app
cd social-media-app
Copy after login

Now we need to initialize an empty Node.js project in the folder. Run the following command:

npm init
Copy after login

This will walk you through some basic setup when creating a new project. Follow the prompts (npm init -y can be done quickly), and in the last step make sure the "main" file name is the same as the entry file you want to use in your project (usually named "app.js").

{
  "name": "social-media-app",
  "version": "1.0.0",
  "description": "A simple social media app built with Node.js",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Copy after login
  1. Install necessary dependencies

Next, we need to install some necessary dependencies, including:

  • Express: We will use This lightweight framework to handle HTTP routing and requests
  • Body-parser: When processing POST requests, we need to parse the data in the request body through the body-parser middleware
  • EJS: We This template engine will be used to render our pages

Install these dependencies through the following command:

npm install express body-parser ejs --save
Copy after login

After installation, you can see in your package.json file The following dependencies appear:

  "dependencies": {
    "body-parser": "^1.18.3",
    "ejs": "^2.6.1",
    "express": "^4.16.4"
  }
Copy after login
  1. Create the application entry file

We have installed the necessary dependencies, now let us create the application entry file "app.js ". First, import the Express and Body-parser modules:

const express = require('express');
const bodyParser = require('body-parser');
Copy after login

Next create an Express application:

const app = express();
Copy after login

Enable body-parser to parse the data in the request body. We choose to parse the data into JSON, so add the following lines to app.js:

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
Copy after login

Use the EJS template engine to render the page. In this application, we will use EJS to render our templates. To enable it, add the following line in the app.js file:

app.set('view engine', 'ejs');
Copy after login

Finally, launch the application in the app.js file:

app.listen(3000, () => console.log('Server running on port 3000!'))
Copy after login

With this simple application, we can Make sure everything is set up correctly and you can now run the program by typing the following command in the terminal:

node app.js
Copy after login
Copy after login

Open http://localhost:3000 in your browser and you should see a "Cannot GET" message.

  1. Add routes and controllers

Now let’s add routes and corresponding controllers to our application. We will create two pages:

  • Home page (show all messages)
  • Publish page (publish new messages)

(1) Home page routing and Controller

To handle home page requests we need to create a route for the / path. We also need a controller to get all the messages and pass them to the view.

First, create a folder and name the file "controllers", and create a file named "home.js" in it. Here is our controller:

// controllers/home.js

let messages = [
  { id: 1, title: 'First Message', body: 'This is the first message' },
  { id: 2, title: 'Second Message', body: 'This is the second message' }
];

exports.getHomePage = (req, res) => {
  res.render('pages/home', { messages });
};
Copy after login

This controller simply passes an array containing two messages to the home.ejs template and renders it.

Now, we need to create a route in the app.js file to handle the / path:

const homeController = require('./controllers/home');

app.get('/', homeController.getHomePage);
Copy after login

The route will create a route for the "GET" request, pointing to our file in controllers/home.js getHomePage function defined in.

(2) Publish page routing and controller

Next, we will create a file for the publish routing and corresponding controller. In the "Controllers" folder, create a file called "publish.js" with the following content:

// controllers/publish.js

let messages = [
  { id: 1, title: 'First Message', body: 'This is the first message' },
  { id: 2, title: 'Second Message', body: 'This is the second message' }
];

exports.getPublishPage = (req, res) => {
  res.render('pages/publish');
};

exports.publishMessage = (req, res) => {
  const { title, body } = req.body;
  const id = messages.length + 1;
  messages.push({ id, title, body });

  res.redirect('/');
};
Copy after login

This controller defines two behaviors:

  • getPublishPage : This function will render a form with a title and body, allowing the user to submit a new message.
  • publishMessage: This function will receive the data submitted by the user and add the new message to the "messages" array, then redirect back to the home page.

Let’s create this route in the app.js file:

const publishController = require('./controllers/publish');

app.get('/publish', publishController.getPublishPage);

app.post('/publish', publishController.publishMessage);
Copy after login

This will create two routes for the /publish path: a GET request route for rendering the form, and a POST Request routing is used to submit data.

  1. Create views

We have created two routes and corresponding controllers, now we need to create the corresponding views in views.

We need to create two folders: a folder named "layouts" and a folder named "pages".

Create a file named "main.ejs" in the "layouts" folder, containing common elements for all website pages, such as titles, page scripts, and stylesheets. The following is the content of this file:

<!-- layouts/main.ejs -->

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Social Media App</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
  <header>
    <h1>Social Media App</h1>
    <nav>
      <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/publish">Publish</a></li>
      </ul>
    </nav>
  </header>

  <main>
    <%- body %>
  </main>

  <footer>
    &copy; 2020 Social Media App
  </footer>
</body>
</html>
Copy after login

在“pages”文件夹中,创建两个名为“home.ejs”和“publish.ejs”的文件。

以下是“home.ejs”文件的内容:

<!-- views/pages/home.ejs -->

<h2>Messages</h2>

<ul>
  <% messages.forEach(message => { %>
    <li><%= message.title %>: <%= message.body %></li>
  <% }) %>
</ul>
Copy after login

这呈现了一个包含所有消息的列表。

以下是“publish.ejs”文件的内容:

<!-- views/pages/publish.ejs -->

<h2>Publish Message</h2>

<form method="POST" action="/publish">
  <label for="title">Title:</label>
  <input type="text" name="title" id="title"><br>

  <label for="body">Body:</label>
  <textarea name="body" id="body"></textarea><br>

  <button type="submit">Publish</button>
</form>
Copy after login

这个文件包含一个表单,用户可以在其中输入新消息的标题和正文。

现在,该应用程序已准备就绪,可以运行。在终端中运行以下命令:

node app.js
Copy after login
Copy after login

在浏览器中输入http://localhost:3000,您应该会看到一个包含所有消息的列表,并能够通过单击链接到发布页面。

  1. 完成

如果您想了解更多关于如何使用Node.js开发Web应用程序或其他Node.js开发内容,请用以上代码示例作为参考,并根据您自己的需求和想法进行更改。现在,您已经拥有了一个基于Node.js的简单社交媒体平台,您可以使用类似的技术来扩展功能,构建更大、更复杂的社交媒体平台。

The above is the detailed content of How to build a simple social media platform using Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!