search
HomeWeb Front-endJS TutorialHow to build a simple social media platform using Node.js

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

Nov 08, 2023 am 11:05 AM
nodejssocial mediabuild

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

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

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

npm init

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"
}
  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

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"
  }
  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');

Next create an Express application:

const app = express();

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())

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');

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

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

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

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 });
};

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);

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('/');
};

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);

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 id="Social-Media-App">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>

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

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

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

<h2 id="Messages">Messages</h2>

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

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

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

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

<h2 id="Publish-Message">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>

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

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

node app.js

在浏览器中输入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!

Statement
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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools