步骤 1:创建项目文件
新建名为 app.js
的文件,添加以下代码:
// 1. 导入内置 http 模块
const http = require('http');
// 2. 创建服务器实例
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
// 返回响应内容
res.end('欢迎学习nodejs课程');
});
// 3. 监听端口
const PORT = 8090;
server.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
步骤 2:使用 WebStorm 运行
打开项目:
启动 WebStorm
选择
File
>Open
,定位到包含app.js
的目录
运行配置:
右键点击
app.js
文件选择
Run 'app.js'
或使用快捷键
Ctrl + Shift + F10
(Windows/Linux) /^ + R
(Mac)
查看输出:
下方
Run
控制台将显示:
步骤 3:访问页面
浏览器访问:http://localhost:8090
关键代码解释
代码部分 | 功能说明 |
---|---|
require('http') |
导入 Node.js 内置 HTTP 模块 |
http.createServer() |
创建服务器实例 |
res.writeHead(200, {...}) |
设置 HTTP 状态码和响应头 |
res.end() |
结束响应并发送内容 |
server.listen(8090) |
绑定端口并启动监听 |
常见问题解决
1.端口冲突:
错误提示:Error: listen EADDRINUSE: address already in use :::8090
解决方案:
关闭占用端口的程序:
kill -9 $(lsof -ti:8090)
(Mac/Linux)修改代码中的端口号
2.中文乱码:
确保响应头包含
charset=utf-8
:res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
3.修改响应内容:
修改
res.end()
中的字符串即可更新页面显示
WebStorm 调试配置
点击工具栏
Add Configuration
➕选择
Node.js
配置项:
- Node interpreter: 确保选择正确 Node 版本
JavaScript file: 选择
app.js
使用
Debug
模式运行(快捷键Shift + F9
)