Nodejs--如何获取前端请求
我们要注意的是,require不是直接获取前端请求,而是用来加载其它js模块
当我们处理前端请求时,要先引入http模块或者express等模块
require
它的核心作用就是模块加载机制,用于导入其他 JavaScript 模块(如内置模块、第三方模块或自定义模块)
流程:
-
使用
require
加载处理请求的模块
例如,加载 Node.js 内置的http
模块来创建服务器:const http = require('http'); // 加载http模块
-
通过加载的模块处理前端请求
用http
模块创建服务器,监听并处理前端发送的请求:const http = require('http');// 创建服务器 const server = http.createServer((req, res) => {// req 是前端请求对象(包含请求地址、方法、参数等)// res 是响应对象(用于向前端返回数据)res.writeHead(200, { 'Content-Type': 'text/plain' });res.end('Hello from Node.js server!\n'); });// 监听端口 server.listen(3000, () => {console.log('Server running at http://localhost:3000/'); });
-
第三方框架的情况
若使用 Express 框架,同样先用require
加载框架,再处理请求:const express = require('express'); // 加载express模块 const app = express();// 处理GET请求 app.get('/', (req, res) => {res.send('Hello from Express!'); });app.listen(3000);
- 处理前端请求的核心是通过
http
模块、Express 等工具,这些工具需要先用require
导入后才能使用。 - 前端请求的具体信息(如 URL、参数、请求体等)会通过回调函数的参数(如
req
对象)传递给开发者。