>웹 프론트엔드 >JS 튜토리얼 >Express.js 전체 가이드

Express.js 전체 가이드

PHPz
PHPz원래의
2024-08-16 06:27:32673검색

Express.js Full Guide

Express.js 소개

1. 설치 및 설정

Express.js는 웹 및 모바일 애플리케이션을 위한 강력한 기능 세트를 제공하는 최소한의 유연한 Node.js 웹 애플리케이션 프레임워크입니다. 서버 측 애플리케이션 및 API 구축, HTTP 요청 처리, 미들웨어 관리를 단순화합니다.

Express.js 설치 및 설정 단계:

  1. Node.js 설치:

    • Express.js에는 Node.js가 필요합니다. 아직 설치되지 않은 경우 공식 웹사이트에서 Node.js를 다운로드하여 설치하세요.
  2. 새 프로젝트 디렉토리 만들기:

   mkdir my-express-app
   cd my-express-app
  1. 새 Node.js 프로젝트 초기화:
   npm init -y

이 명령은 기본 설정으로 package.json 파일을 생성합니다.

  1. Express.js 설치:
   npm install express

이 명령은 Express.js를 설치하고 이를 package.json 파일에 종속성으로 추가합니다.

  1. nodemon 설치:
    • nodemon은 파일 변경이 감지되면 애플리케이션을 자동으로 다시 시작하는 도구입니다.
   npm install --save-dev nodemon
  1. package.json 스크립트에 nodemon 추가: package.json을 열고 다음을 포함하도록 스크립트 섹션을 수정합니다.
   "scripts": {
     "start": "nodemon app.js"
   }
  1. JavaScript에 대한 가져오기 구문 설정:

    • Node.js는 기본적으로 파일에서 직접 ES6 모듈 구문(가져오기/내보내기)을 지원하지 않습니다. package.json에 "type": "module"을 추가하여 이 기능을 활성화해야 합니다.
    • 다음을 포함하도록 package.json을 수정합니다.
     "type": "module"
    
  2. 진입점 파일 만들기:
    프로젝트 디렉터리에 app.js(또는 index.js)라는 파일을 만듭니다. 이 파일에는 Express 애플리케이션 코드가 포함됩니다.

2. 기본 Express 애플리케이션 생성

기본 Express 애플리케이션을 만들려면 다음 단계를 따르세요.

  1. app.js에서 Express 초기화:
   import express from 'express';
   const app = express();
   const port = 3000;

   app.get('/', (req, res) => {
     res.send('Hello, World!');
   });

   app.listen(port, () => {
     console.log(`Server is running on http://localhost:${port}`);
   });
  • 'express'에서 익스프레스를 가져옵니다. ES6 가져오기 구문을 사용하여 Express 모듈을 가져옵니다.
  • express()는 Express 애플리케이션을 초기화합니다.
  • app.get()은 루트 URL(/)에 대한 GET 요청에 대한 경로 핸들러를 정의합니다.
  • app.listen()은 서버를 시작하고 지정된 포트에서 수신 대기합니다.
  1. 애플리케이션 실행:

    • npm start를 사용하여 nodemon으로 애플리케이션을 실행합니다.
     npm start
    
  • 웹 브라우저를 열고 http://localhost:3000으로 이동합니다. "Hello, World!"가 표시되어야 합니다. 표시됩니다.

이러한 단계를 통해 ES6 가져오기 구문을 사용하여 기본 Express.js 애플리케이션을 설정하고 개발 중에 서버를 자동으로 다시 시작하도록 nodemon을 구성했습니다. 이 설정은 개발을 간소화하고 코드 변경 사항을 효율적으로 처리하는 데 도움이 됩니다.

Express.js의 라우팅

Express.js의 라우팅은 애플리케이션이 특정 엔드포인트에 대한 클라이언트 요청에 응답하는 방법을 정의하는 프로세스입니다. 다양한 HTTP 메소드(GET, POST, PUT, DELETE 등)에 대해 경로를 정의할 수 있으며 복잡한 URL 구조를 처리하도록 구성할 수 있습니다.

기본 GET 경로

GET 경로는 서버에서 데이터를 검색하는 데 사용됩니다. 쿼리를 기반으로 정적 콘텐츠나 데이터를 제공하는 데 자주 사용됩니다.

예:

// Basic GET route
app.get('/home', (req, res) => {
  res.send('Welcome to the Home Page!');
});
기본 POST 경로

POST 경로는 서버에 데이터를 보내는 데 사용됩니다. 일반적으로 양식을 제출하거나 새로운 리소스를 생성하는 데 사용됩니다.

예:

// Basic POST route
app.post('/submit', (req, res) => {
  res.send('Form submitted!');
});
기본 PUT 경로

PUT 경로는 서버의 기존 데이터를 업데이트하는 데 사용됩니다. 일반적으로 리소스를 수정하거나 레코드를 업데이트하는 데 사용됩니다.

예:

// Basic PUT route
app.put('/update', (req, res) => {
  res.send('Data updated!');
});
기본 삭제 경로

DELETE 경로는 서버에서 데이터를 제거하는 데 사용됩니다. 리소스나 기록을 삭제할 때 사용됩니다.

예:

// Basic DELETE route
app.delete('/delete', (req, res) => {
  res.send('Data deleted!');
});

Express.js의 app.use

Express.js의 app.use 메소드는 요청을 처리하는 미들웨어 기능을 등록하는 데 사용됩니다. 미들웨어 기능은 정의된 순서대로 실행되며 app.use를 사용하여 미들웨어를 전역적으로 적용하거나 특정 경로에 적용할 수 있습니다.

1. 미들웨어 글로벌 적용

경로 없이 app.use를 사용하면 들어오는 모든 요청에 ​​미들웨어 기능이 적용됩니다. 이는 로깅, 요청 본문 구문 분석 또는 세션 처리와 같은 전역 기능을 설정하는 데 유용합니다.

예:

// Middleware function applied globally
app.use((req, res, next) => {
  console.log(`Request URL: ${req.url}`);
  next(); // Pass control to the next handler
});

app.get('/', (req, res) => {
  res.send('Home Page');
});
  • Global Middleware: The middleware function logs the request URL for every request received by the server.

2. Applying Middleware to Specific Paths

You can use app.use to apply middleware only to requests that match a specific path. This allows you to target middleware to certain routes.

Example:

// Middleware function applied to /admin paths
app.use('/admin', (req, res, next) => {
  console.log('Admin route accessed');
  next(); // Pass control to the next handler
});

app.get('/admin/dashboard', (req, res) => {
  res.send('Admin Dashboard');
});

app.get('/user/profile', (req, res) => {
  res.send('User Profile');
});
  • Path-Specific Middleware: The middleware logs a message only for requests to paths starting with /admin.

3. Using app.use with Multiple Middleware Functions

You can chain multiple middleware functions together with app.use, allowing for sequential processing of requests.

Example:

// First middleware function
const firstMiddleware = (req, res, next) => {
  console.log('First Middleware');
  next(); // Proceed to the next middleware
};

// Second middleware function
const secondMiddleware = (req, res, next) => {
  console.log('Second Middleware');
  next(); // Proceed to the next handler
};

// Apply multiple middleware functions
app.use(firstMiddleware, secondMiddleware);

app.get('/', (req, res) => {
  res.send('Home Page');
});
  • Chaining Middleware: firstMiddleware and secondMiddleware are executed sequentially for all requests.

The app.use method in Express.js provides flexibility for applying middleware functions globally or to specific routes, and for processing requests in a modular fashion.

Callback Functions in Express.js

In Express.js, callback functions are crucial for handling HTTP requests. They are used in middleware and route handlers to process requests and manage responses.

1. Parameters in Callback Functions

Callback functions in Express.js receive three parameters:

  • req (Request): The request object containing details about the incoming request.
  • res (Response): The response object used to send a response to the client.
  • next (Next): A function to pass control to the next middleware or route handler.

Example:

function callback(req, res, next) {
  // Your code here
  next(); // Pass control to the next middleware or route handler
}

2. Middleware Callbacks

Middleware functions process requests before they reach route handlers. They utilize the req, res, and next parameters.

Example:

const logMiddleware = (req, res, next) => {
  console.log(`Request URL: ${req.url}`);
  next(); // Pass control to the next handler
};

app.use(logMiddleware); // Apply middleware globally

app.get('/', (req, res) => {
  res.send('Home Page');
});

3. Route Handler Callbacks

Route handlers define responses for specific routes, using callback parameters to manage requests and responses.

Example:

app.get('/example', (req, res) => {
  res.send('Hello World!');
});

4. Chaining Middleware Functions

Multiple middleware functions can be chained together to handle requests sequentially.

Example:

const authenticate = (req, res, next) => {
  console.log('Authentication middleware');
  next(); // Proceed to the next middleware
};

const authorize = (req, res, next) => {
  console.log('Authorization middleware');
  next(); // Proceed to the route handler
};

app.get('/profile', authenticate, authorize, (req, res) => {
  res.send('User Profile');
});

Route Parameters in Express.js

Route parameters are dynamic segments of a URL used to capture values from the URL path. They allow you to define routes that can handle variable input, making your routes more flexible.

1. Basic Route Parameters

Route parameters are defined in the route path by using a colon : followed by the parameter name. You can access these parameters in your route handler through the req.params object.

Example:

// Route with a route parameter
app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});
  • Route Parameter: The :id in the route path is a parameter that captures the value from the URL, accessible via req.params.id.

2. Multiple Route Parameters

You can define multiple route parameters in a single route path, allowing for more complex URL structures.

Example:

// Route with multiple route parameters
app.get('/post/:year/:month/:day', (req, res) => {
  const { year, month, day } = req.params;
  res.send(`Post date: ${year}-${month}-${day}`);
});
  • Multiple Parameters: The :year, :month, and :day parameters capture parts of the date from the URL, accessible via req.params.year, req.params.month, and req.params.day.

3. Optional Route Parameters

Route parameters can also be optional. Use a question mark ? to indicate optional segments in the route path.

Example:

// Route with an optional route parameter
app.get('/product/:id?', (req, res) => {
  const productId = req.params.id || 'not specified';
  res.send(`Product ID: ${productId}`);
});
  • Optional Parameter: The :id? parameter is optional, meaning the route can be accessed with or without this parameter.

Route parameters provide a way to build dynamic and flexible routes in Express.js, allowing you to handle various input values and create more sophisticated URL patterns.

req Object

In Express.js, the req object represents the incoming HTTP request from the client. It includes details about the request such as URL, headers, and body. Properly understanding the req object is crucial for handling requests effectively.

req.body

The req.body property contains data sent in the request body, typically used in POST and PUT requests. To access req.body, you need to use middleware for parsing the request data.

Handling JSON Data:

app.use(express.json()); // Middleware to parse JSON bodies

app.post('/submit', (req, res) => {
  const { name, age } = req.body;
  res.send(`Received data - Name: ${name}, Age: ${age}`);
});
  • Explanation:
    • express.json(): Middleware to parse JSON data in request bodies.
    • req.body: Contains parsed JSON data.

Handling URL-encoded Data:

app.use(express.urlencoded({ extended: true })); // Middleware to parse URL-encoded bodies

app.post('/submit', (req, res) => {
  const { name, age } = req.body;
  res.send(`Received data - Name: ${name}, Age: ${age}`);
});
  • Explanation:
    • express.urlencoded({ extended: true }): Middleware to parse URL-encoded data from forms.
    • req.body: Contains parsed URL-encoded data.

req.cookies

The req.cookies property contains cookies sent by the client. To use req.cookies, you need the cookie-parser middleware to parse cookies in requests.

Example:

import cookieParser from 'cookie-parser';
app.use(cookieParser()); // Middleware to parse cookies

app.get('/check-cookies', (req, res) => {
  const user = req.cookies.user; // Access a cookie named 'user'
  res.send(`Cookie value - User: ${user}`);
});
  • Explanation:
    • cookieParser(): Middleware to parse cookies from request headers.
    • req.cookies: Contains cookies sent by the client.

req.method

The req.method property contains the HTTP method of the incoming request. This can be useful for handling different types of requests, such as GET, POST, PUT, DELETE, etc.

Example:

app.use((req, res, next) => {
  console.log(`Request Method: ${req.method}`); // Logs the HTTP method of the request
  next(); // Pass control to the next handler
});

app.get('/example', (req, res) => {
  res.send(`This is a GET request`);
});

app.post('/example', (req, res) => {
  res.send(`This is a POST request`);
});
  • Explanation:
    • req.method: Contains the HTTP method used for the request (e.g., GET, POST).

req.params

The req.params property contains route parameters specified in the URL path. Route parameters are used to capture values from the URL and are typically defined in routes with a colon syntax (e.g., /users/:id).

Example:

app.get('/users/:id', (req, res) => {
  const userId = req.params.id; // Access the route parameter 'id'
  res.send(`User ID: ${userId}`);
});
  • Explanation:
    • req.params: Contains key-value pairs of route parameters, where the key is the parameter name defined in the route, and the value is the actual value from the URL.

req.query

The req.query property contains query string parameters from the URL. These are typically used to pass data in the URL for GET requests.

Example:

app.get('/search', (req, res) => {
  const query = req.query.q; // Access the query parameter 'q'
  res.send(`Search query: ${query}`);
});
  • Explanation:
    • req.query: Contains key-value pairs of query string parameters. For example, for a URL like /search?q=example, req.query.q would be 'example'.

req.get()

The req.get() method is used to retrieve HTTP headers from the incoming request. It allows you to access specific headers by name. This is useful for extracting metadata about the request or for handling custom headers.

Example:

app.get('/headers', (req, res) => {
  const userAgent = req.get('User-Agent'); // Access the 'User-Agent' header
  const host = req.get('Host'); // Access the 'Host' header
  const acceptLanguage = req.get('Accept-Language'); // Access the 'Accept-Language' header
  const contentType = req.get('Content-Type'); // Access the 'Content-Type' header

  res.send(`
    User-Agent: ${userAgent}0c6dc11e160d3b678d68754cc175188a
    Host: ${host}0c6dc11e160d3b678d68754cc175188a
    Accept-Language: ${acceptLanguage}0c6dc11e160d3b678d68754cc175188a
    Content-Type: ${contentType}
  `);
});
  • Explanation:
    • req.get('User-Agent'): Retrieves the User-Agent header, which provides information about the client's browser or application.
    • req.get('Host'): Retrieves the Host header, which indicates the domain name of the server and port number.
    • req.get('Accept-Language'): Retrieves the Accept-Language header, which indicates the preferred language(s) for the response.
    • req.get('Content-Type'): Retrieves the Content-Type header, which specifies the media type of the request body.

res Object

In Express.js, the res object represents the HTTP response that is sent back to the client. It is used to set response headers, status codes, and to send data or files back to the client. Understanding the res object is essential for controlling the response sent from the server.

res.append()

The res.append() method is used to add additional headers to the response. It is useful when you need to modify or add headers dynamically before sending the response.

Example:

app.get('/set-headers', (req, res) => {
  res.append('Custom-Header', 'HeaderValue'); // Add a custom header
  res.append('Another-Header', 'AnotherValue'); // Add another header
  res.send('Headers have been set!');
});
  • Explanation:
    • res.append(name, value): Adds a header with the specified name and value to the response. If the header already exists, the new value is appended to the existing values.

res.cookie()

The res.cookie() method is used to set cookies on the client's browser. It allows you to send cookies with specific options such as expiration, path, and secure flags.

Example:

app.get('/set-cookie', (req, res) => {
  // Set a cookie named 'username' with a value 'JohnDoe'
  res.cookie('username', 'JohnDoe', {
    maxAge: 24 * 60 * 60 * 1000, // Cookie expires after 1 day
    httpOnly: true,              // Cookie is not accessible via JavaScript
    secure: false,               // Cookie is sent over HTTP (not HTTPS)
    path: '/'                    // Cookie is valid for the entire domain
  });
  res.send('Cookie has been set');
});
  • Explanation:
    • res.cookie(name, value, [options]): Sets a cookie with the specified name and value. The options parameter can include:
    • maxAge: Expiration time of the cookie in milliseconds.
    • httpOnly: If true, the cookie is not accessible via JavaScript (client-side).
    • secure: If true, the cookie is sent only over HTTPS connections.
    • path: The path for which the cookie is valid.

res.end()

The res.end() method is used to end the response process and send the response to the client. It is often used to send the final output or to close the response stream when no additional data needs to be sent.

Example:

app.get('/finish', (req, res) => {
  res.end('Response has been sent and the connection is closed.');
});
  • Explanation:
    • res.end([data], [encoding]): Ends the response process. If data is provided, it is sent as the response body. The encoding parameter specifies the character encoding for the data. If no data is provided, an empty response is sent.

res.json()

The res.json() method is used to send a JSON response to the client. It automatically sets the Content-Type header to application/json and converts the provided data into a JSON string.

Example:

app.get('/data', (req, res) => {
  const data = {
    name: 'John Doe',
    age: 30,
    city: 'New York'
  };
  res.json(data);
});
  • Explanation:
    • res.json([body]): Sends a JSON response. The body parameter is an object or array that will be converted to a JSON string and sent as the response body. The Content-Type header is set to application/json automatically.

res.location()

The res.location() method sets the Location header of the response. It is commonly used to specify the URL to which a client should be redirected. However, this method does not send a response to the client by itself; it only sets the header.

Example:

app.get('/set-location', (req, res) => {
  res.location('/new-url');
  res.send('Location header has been set');
});
  • Explanation:
    • res.location(url): Sets the Location header to the specified URL. This is often used in conjunction with res.redirect to indicate where the client should be redirected.

res.redirect()

The res.redirect() method sends a redirect response to the client. It sets the Location header and sends a status code (default is 302) to redirect the client to a different URL.

Example:

app.get('/redirect', (req, res) => {
  res.redirect('/new-url');
});
  • Explanation:
    • res.redirect([status,] url): Redirects the client to the specified URL. The optional status parameter allows you to set a custom HTTP status code (e.g., 301 for permanent redirect, 302 for temporary redirect). If no status is provided, 302 is used by default.

res.send()

The res.send() method is used to send a response to the client. It can send a variety of response types, including strings, buffers, objects, or arrays. The method automatically sets the Content-Type header based on the type of the response.

Example:

app.get('/text', (req, res) => {
  res.send('This is a plain text response.');
});

app.get('/json', (req, res) => {
  const data = { message: 'This is a JSON response.' };
  res.send(data);
});

app.get('/buffer', (req, res) => {
  const buffer = Buffer.from('This is a buffer response.');
  res.send(buffer);
});
  • Explanation:
    • res.send([body]): Sends the response to the client. The body parameter can be a string, buffer, object, or array. If an object or array is passed, it will be automatically converted to JSON. The Content-Type header is set based on the type of the body parameter.

res.sendFile()

The res.sendFile() method is used to send a file as the response to the client. It sets the appropriate Content-Type header based on the file type and streams the file to the client.

Example:

import path from 'path';

app.get('/file', (req, res) => {
  const filePath = path.join(__dirname, 'public', 'example.txt');
  res.sendFile(filePath);
});
  • Explanation:
    • res.sendFile(path[, options], [callback]): Sends a file as the response. The path parameter is the absolute path to the file you want to send. The optional options parameter can be used to set additional options such as the Content-Type header or to handle errors. The optional callback parameter is a function that is called when the file has been sent.

res.sendStatus()

The res.sendStatus() method sets the HTTP status code and sends the corresponding status message as the response body. It is a shorthand for setting the status code and sending a response in one step.

Example:

app.get('/status', (req, res) => {
  res.sendStatus(404); // Sends a 404 Not Found status with the message 'Not Found'
});
  • Explanation:
    • res.sendStatus(statusCode): Sets the HTTP status code and sends a response with the status message corresponding to the code. For example, 404 will send 'Not Found' as the response body.

res.set()

The res.set() method sets HTTP headers for the response. It can be used to specify various headers, including custom headers.

Example:

app.get('/headers', (req, res) => {
  res.set('X-Custom-Header', 'Value');
  res.set({
    'Content-Type': 'application/json',
    'X-Another-Header': 'AnotherValue'
  });
  res.send('Headers set');
});
  • Explanation:
    • res.set(name, value): Sets a single HTTP header. name is the header name, and value is the header value.
    • res.set(headers): Sets multiple headers at once by passing an object where keys are header names and values are header values.

res.status()

The res.status() method sets the HTTP status code for the response. This method is used to define the status code before sending the response.

Example:

app.get('/error', (req, res) => {
  res.status(500).send('Internal Server Error'); // Sets status code to 500 and sends the message
});
  • Explanation:
    • res.status(statusCode): Sets the HTTP status code for the response. The status code can then be followed by other methods (like res.send, res.json, etc.) to send the response body.

위 내용은 Express.js 전체 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.