🗣 Wd提问: nodejs搭建本地服务器
🤖 Ai回答: 在 Node.js 中搭建本地服务器非常简单,可以通过内置的 `http` 模块或使用 Express.js 框架来实现。以下是两种方式的详细步骤:
✅ 方法一:使用原生 `http` 模块(适合学习和简单项目)
1、创建项目文件夹并初始化
bash
mkdir my-server
cd my-server
npm init -y
2、创建 `server.js` 文件
js
const http = require('http');
const server = http.createServer((req, res) = {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, this is a local Node.js server!');
});
const PORT = 3000;
server.listen(PORT, 'localhost', () = {
console.log(`Server running at http://localhost:${PORT}/`);
});
3、启动服务器
bash
node server.js
访问:[http://localhost:3000](http://localhost:3000)
✅ 方法二:使用 Express.js(推荐用于实际开发)
1、安装 Express
bash
npm install express
2、创建 `app.js` 文件
js
const express = require('express');
const app = express();
const PORT = 3000;
// 静态文件服务(可选)
app.use(express.static('public'));
// 路由示例
app.get('/', (req, res) = {
res.send('<h1Hello from Express!</h1');
});
app.get('/api/data', (req, res) = {
res.json({ message: This is JSON data, timestamp: new Date() });
});
app.listen(PORT, () = {
console.log(`Express server running at http://localhost:${PORT}/`);
});
3、启动服务器
bash
node app.js
访问:
[http://localhost:3000](http://localhost:3000)
[http://localhost:3000/api/data](http://localhost:3000/api/data)
🛠️ 小贴士
如果要自动重启服务器(开发时),可以安装 `nodemon`:
bash
npm install -g nodemon
nodemon server.js
可以用 `public/` 目录存放 HTML、CSS、JS 等静态资源。
如果你是初学者,建议从 方法一 开始;如果是做 Web 应用,强烈推荐 方法二(Express)。
需要我帮你创建一个带路由、中间件、静态文件的完整模板吗?欢迎继续提问!🚀
📣 商家广告 :
👍
0
👎
IP地址: 120.72.2.51
搜索次数: 13
提问时间: 2025-12-09 20:49:05
本站所有
❓
问答
均由Ai自动分析整理,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
本站由
🟢
豌豆Ai
提供技术支持,使用的最新版:
豌豆Ai站群搜索引擎系统 V.25.10.25
搭建本站。