🗣 Wd提问: nodejs创建服务器
🤖 Ai回答: 在 Node.js 中创建一个简单的服务器非常容易,可以使用内置的 `http` 模块来实现。下面是一个基础示例:
1、创建一个基本 HTTP 服务器
javascript
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) = {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/plain' });
// 发送响应
res.end('Hello, World!\n');
});
// 监听端口
const PORT = 3000;
server.listen(PORT, () = {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
2、保存并运行
将上面的代码保存为 `server.js`,然后在终端中运行:
bash
node server.js
打开浏览器访问 `http://localhost:3000`,你应该能看到 Hello, World!。
3、响应不同路径(简单路由)
你可以扩展服务器以处理不同的请求路径:
javascript
const http = require('http');
const server = http.createServer((req, res) = {
res.writeHead(200, { 'Content-Type': 'text/html' });
if (req.url === '/') {
res.end('<h1首页</h1');
} else if (req.url === '/about') {
res.end('<h1关于页面</h1');
} else {
res.end('<h1404 页面未找到</h1');
}
});
server.listen(3000, () = {
console.log('服务器运行在 http://localhost:3000');
});
4、使用 Express(推荐)
虽然原生 `http` 模块很强大,但通常建议使用 [Express](https://expressjs.com/) 框架来简化开发:
bash
npm init -y
npm install express
javascript
const express = require('express');
const app = express();
app.get('/', (req, res) = {
res.send('<h1Hello, World!</h1');
});
app.get('/about', (req, res) = {
res.send('<h1关于页面</h1');
});
app.listen(3000, () = {
console.log('服务器运行在 http://localhost:3000');
});
✅ 总结
使用 `http.createServer()` 创建服务器。
处理请求和响应。
推荐使用 Express 来构建更复杂的 Web 应用。
如果你有特定需求(如 API、静态文件服务、WebSocket 等),也可以继续深入!
📣 商家广告:





0
IP地址: 202.106.181.79
搜索次数: 1
提问时间: 2025-11-10 20:19:11
🛒 域名购买:
990.net.cn
cdn.hk.cn
bc0.cn
6.hn.cn
815.red
yw.gs
souru.com.cn
8.sx.cn
yq.gs
lr.gs
❓️ 热门提问:
怎么进公司服务器
查看服务器上的时间
站群系统黑帽
电脑主机按不亮
Discuz源码广告系统
云电脑多少钱一天
双线服务器托管费用
机房防静电地板多少钱一平米
电脑挂机项目
云挂机宝vps
豌豆Ai站群搜索引擎系统
🌐 域名评估:
twks.cn
chxk.cn
yu7.xz.cn
pztz.cn
xphone.beauty
r-t.com.cn
alhl.cn
wy.gs
jdmd.cn
gnrt.cn
⛏ 最新挖掘:
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜
🖌 热门作画:
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊:
🔗 友情链接:
검색엔진
查搜
ai提问
🧰 站长工具:
Ai工具 whois查询 搜索
📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。