In Node.js, web page jump is a common function of web applications. It allows us to take the user from one page to another and then update the URL and browser history while displaying the new page content.
In this article, we will explore how to use Node.js to jump to web pages. We will discuss the following topics:
Basic knowledge
The basis of web page jump isHTTP redirection
. A redirect is an HTTP response code used to tell the browser to load a new URL.
Common HTTP redirects include:
To jump to the web page, we need to send the response code and the new URL as the response header .
Use Express.js for web page jump
Express.js is one of the most popular web frameworks in Node.js, which makes building web applications simple.
In Express.js, web page jump can be achieved through the res.redirect()
method. This method takes a required parameter representing the redirected URL, for example:
app.get('/old-url', (req, res) => { res.redirect('/new-url'); });
This will redirect users to /new-url# when they visit
/old-url ##. Express.js automatically sends a 302 redirect response code.
app.get('/old-url', (req, res) => { res.redirect(301, '/new-url'); });
/old-url to
/new-url:
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/old-url') { res.writeHead(301, { 'Location': '/new-url' }); res.end(); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<h1>Hello, World!</h1>'); res.end(); } }); server.listen(3000);
res.writeHead() method sets the response code and
Location header to cause the browser to load the new URL.
Open Redirect Vulnerability and is often used to spread malware or steal user data.
The above is the detailed content of How to use Node.js to jump to web pages. For more information, please follow other related articles on the PHP Chinese website!