Home >Web Front-end >JS Tutorial >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.
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.
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" }
Next, we need to install some necessary dependencies, including:
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" }
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.
Now let’s add routes and corresponding controllers to our application. We will create two pages:
(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:
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.
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> © 2020 Social Media App </footer> </body> </html>
在“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>
这呈现了一个包含所有消息的列表。
以下是“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>
这个文件包含一个表单,用户可以在其中输入新消息的标题和正文。
现在,该应用程序已准备就绪,可以运行。在终端中运行以下命令:
node app.js
在浏览器中输入http://localhost:3000,您应该会看到一个包含所有消息的列表,并能够通过单击链接到发布页面。
如果您想了解更多关于如何使用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!