🗣 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地址: 93.96.203.219
搜索次数: 0
提问时间: 2025-11-09 00:06:04
🛒 域名购买 :
85.chat 219.net.cn 757.net.cn 6.ac.cn jiu.red 4448.com.cn pai.pw 41.gold n-f.cn 27.gold
❓️ 热门提问 :
ip不变怎么回事 香港户口多少钱 green下载 3日本服务器vps idc云服务商 cards域名 内蒙古云服务器 内网dns域名解析 香港免费 云主机 云主机哪个好 豌豆Ai站群搜索引擎系统
🌐 域名评估 :
y-w.com.cn su7.hn.cn qrks.cn evtol.mo.cn uj.gs m.tj.cn car.hi.cn dpat.cn starfair.org.cn aaaa.bj.cn
⛏ 最新挖掘 :
凯里酸汤鱼 贵阳烤脑花 都匀毛尖茶 花溪牛肉粉 贵阳烤生蚝 贵阳烤豆腐 贵阳纸包鱼 贵阳特色菜
🖌 热门作画 :
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊 :
🔗 友情链接 :
google站群
日本の検索エンジン
ai提问
🧰 站长工具 :Ai工具 whois查询 搜索
📢 温馨提示 :本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持 :本站由豌豆Ai 提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。