Home > Article > Web Front-end > How to build a server in nodejs
Steps to build a Node.js server: Preparation: Install the Node.js environment, text editor and terminal tools. Initialize the project: Create the project folder and use npm to initialize the project. Install the Express framework: Use npm to install Express. Create the server file: Create the server.js file as the server file. Write server code: Write Express code in server.js. Run the server: Use the node server.js command to start the server. Access the server: Visit http://localhost:3000 in the browser.
nodejsHow to build a server
1. Preparation
Before building a nodejs server, you need to prepare the following:
2. Construction steps
Create project folder
Create a folder for storage Server code.
Initialize the project
In the project folder, use npm (nodejs package manager) to initialize a project, the command is as follows:
<code>npm init -y</code>
Install Express Framework
Express is a nodejs framework for building web applications. Install it using npm with the following command:
<code>npm install --save express</code>
Create server file
In the project folder, create a new file like server.js
, as a server file.
Write server code
In the server.js
file, write the following code:
<code>const express = require("express"); const app = express(); app.get("/", (req, res) => { res.send("Hello world!"); }); app.listen(3000, () => { console.log("Server listening on port 3000"); });</code>
Run the server
In the terminal, switch to the project folder and run the following command to start the server:
<code>node server.js</code>
3. Access the server
After the server is started, you can view the server response by accessing http://localhost:3000
in the browser.
The above is the detailed content of How to build a server in nodejs. For more information, please follow other related articles on the PHP Chinese website!