GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.runoob.com — Node.js 构建简单应用 | 菜鸟教程
Node.js 教程
Node.js 教程
Node.js 概念
Node.js 安装配置
Node.js VS Code
Node.js NVM
Node.js 创建第一个应用
Node.js 工作机制
NPM 使用介绍
PNPM 使用介绍
Node.js REPL
Node.js 异步编程
Node.js 回调函数
Node.js Promise
Node.js async/await
Node.js 事件循环
Node.js EventEmitter
Node.js Buffer
Node.js Stream
Node.js 模块系统
Node.js 模块导入
Node.js 函数
Node.js 路由
Node.js 全局对象
Node.js 常用工具
Node.js 文件系统
Node.js 内置模块
Node.js 测验
Node.js 应用Node.js 构建简单应用 Node.js GET/POST请求 Node.js util 模块 Node.js Web 模块 Node.js Express 框架 Node.js RESTful API Node.js 多进程 Node.js JXcore 打包 Node.js MySQL Node.js MongoDB npx 入门教程Node.js 构建简单应用在 Node.js 中构建一个简单应用通常包括以下几个步骤:
接下来,我们将一步步介绍如何用 Node.js 构建一个简单的 HTTP 应用程序。 1、安装 Node.js首先确保系统上已安装 Node.js 和 npm,可以在命令行中输入以下命令进行验证: node -v npm -v 如果还未安装,请参考:Node.js 安装配置。 2、创建项目文件夹在终端中,创建一个项目文件夹 my-first-node-app 并进入该文件夹: mkdir my-first-node-app cd my-first-node-app 3、初始化项目通过 npm init 命令生成 package.json 文件,它包含了项目的配置信息。 运行以下命令并按提示填写信息(可以直接按回车跳过): npm init -y 把 package.json 文件修改为以下内容: {
"name": "my-first-node-app",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {}
}
4、创建应用入口文件在项目根目录 my-first-node-app 下创建一个 app.js 文件,这是应用的入口文件,用于设置服务器和处理请求。 5、编写服务器代码在 app.js 文件中编写以下代码,用于创建一个简单的 HTTP 服务器: 实例
const http = require('http'); // 创建服务器 const server = http.createServer((req, res) => { // 设置HTTP响应的状态码和头信息 res.writeHead(200, { // 设置内容类型为 HTML,并指定字符集为 UTF-8,这样中文不会乱码 'Content-Type': 'text/html; charset=utf-8' }); // 发送响应体 res.end('<h1>Hello, World!</h1><p>这是我的第一个 Node.js 应用。</p>'); }); // 监听端口 const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); 6、运行服务器在项目根目录下执行以下命令,启动服务器: npm start 你会看到控制台输出如下信息: Server is running on http://localhost:3000 7、访问服务器打开浏览器并访问 http://localhost:3000,你会看到页面显示如下:
说明服务器已经成功运行。 8、添加路由为了处理不同的请求路径,可以在服务器代码中添加简单的路由,例如: 实例
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to the homepage!'); } else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('This is the about page.'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); 通过上述步骤,你已经构建了一个简单的 Node.js 应用,并且可以处理不同的请求路径。 这个基础应用可以进一步扩展,如添加数据库支持、引入 Express 框架处理复杂路由等,为更复杂的项目奠定基础。
AI 思考中...
点我分享笔记取消
分类导航
Advertisement
|
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |