如何配置Node.js服务器根据URL路径返回对应请求页面
问题:让Node.js服务器根据URL路径返回不同文件
当前使用Node.js服务器时,访问localhost:9090能得到res.write输出的内容,但访问localhost:9090/index.html、localhost:9090/funnyFile/Jokes.html或localhost:9090/myProjects/poj1/index.html等路径时,仍返回相同内容。需要配置服务器根据URL路径提供对应文件。
你的原始服务器代码:
const http = require('express') const port = 9090 // Create a server object: const server = http.createServer(function (req, res) { // Write a response to the client res.write("I choose this text"); // End the response res.end() }) // Set up our server so it will listen on the port server.listen(port, function (error) { // Checking any error occur while listening on port if (error) { console.log('Something went wrong', error); } // Else sent message of listening else { console.log('Server is listening on port' + port); } })
解决方案
首先注意:你的代码错误地将express模块当作http模块引入,正确做法是引入express并创建应用实例,以下是两种实现方式:
方式一:使用Express静态文件中间件(推荐)
Express提供了express.static中间件,可以快速托管静态文件,自动根据URL路径返回对应文件。
- 在项目根目录创建
public文件夹,将所有静态文件按路径放入其中(比如public/funnyFile/Jokes.html、public/myProjects/poj1/index.html) - 修改服务器代码:
const express = require('express'); const port = 9090; const app = express(); // 托管public文件夹下的静态文件 app.use(express.static('public')); app.listen(port, function(error) { if (error) { console.log('Something went wrong', error); } else { console.log('Server is listening on port ' + port); } });
启动服务器后,访问对应URL就能直接返回public文件夹中对应的文件。
方式二:手动处理URL路径(适合理解原理)
如果需要手动控制文件读取逻辑,可以使用fs和path模块实现,同时要注意避免路径遍历安全问题:
const express = require('express'); const fs = require('fs'); const path = require('path'); const port = 9090; const app = express(); app.get('*', function(req, res) { // 基于项目根目录的public文件夹构造绝对路径,防止路径遍历 const filePath = path.join(__dirname, 'public', req.url); // 检查文件是否存在 fs.access(filePath, fs.constants.F_OK, (err) => { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); res.end('<h1>404 Not Found</h1>'); return; } // 根据文件扩展名设置正确的Content-Type const ext = path.extname(filePath); let contentType = 'text/html'; if (ext === '.css') contentType = 'text/css'; else if (ext === '.js') contentType = 'application/javascript'; else if (ext === '.png') contentType = 'image/png'; // 可根据需要添加更多文件类型 // 读取文件并返回给客户端 fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(500, {'Content-Type': 'text/html'}); res.end('<h1>500 Internal Server Error</h1>'); return; } res.writeHead(200, {'Content-Type': contentType}); res.end(data); }); }); }); app.listen(port, function(error) { if (error) { console.log('Something went wrong', error); } else { console.log('Server is listening on port ' + port); } });
同样需要将文件放入public文件夹,该方式手动处理了文件存在性检查、内容类型设置和错误响应。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

