乐闻世界logo
搜索文章和话题

How to redirect to another page from ejs page

1个答案

1

Redirecting from EJS pages is typically not performed directly within the EJS template itself but rather in the server-side code handling HTTP requests. EJS (Embedded JavaScript templating) is a template engine used for rendering HTML pages from the server side; it does not handle client-side or server-side redirects itself. Redirects are typically handled within the server-side route handling logic.

Step 1: Create an Express Server

First, we need to set up a basic Express server. If you haven't installed Express yet, you can install it via npm:

bash
npm install express

Then, create a simple Express server as follows:

javascript
const express = require('express'); const app = express(); app.set('view engine', 'ejs'); // Home route app.get('/', (req, res) => { res.render('index'); }); // Redirect route app.get('/redirect', (req, res) => { // Perform redirect to another route res.redirect('/new-page'); }); // New page route app.get('/new-page', (req, res) => { res.render('new-page'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); });

Step 2: Create EJS Templates

In your project's views folder, you need two EJS template files: index.ejs and new-page.ejs.

For example, index.ejs might look like this:

html
<!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h1>Welcome to the Home Page</h1> <a href="/redirect">Go to New Page</a> </body> </html>

And new-page.ejs could be:

html
<!DOCTYPE html> <html> <head> <title>New Page</title> </head> <body> <h1>This is the New Page</h1> <a href="/">Back to Home</a> </body> </html>

Step 3: Test the Redirect

Now everything is set up; you can start the server and access http://localhost:3000 in your browser. Clicking the "Go to New Page" link should redirect your browser to the new page.

In this example, when a user accesses the /redirect route, the server-side logic calls res.redirect('/new-page') to redirect the user to the /new-page route, which then renders and displays the new-page.ejs template. Thus, the redirect process is completed on the server side, not within the EJS template.

2024年7月20日 03:52 回复

你的答案