跳到主要内容

语法

2024年10月14日
柏拉文
越努力,越幸运

一、Methods


1.1 http.createServer

使用 http.createServer 实现 HTTP 服务器

const http = require('node:http');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});

server.listen(8000, () => {
console.log("HTTP Server is running on port 8000");
});
const http = require('node:http');

const server = http.createServer();

server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});

server.listen(8000, () => {
console.log("HTTP Server is running on port 8000");
});

1.2 koa http.createServer

使用Koahttp.createServer 实现 HTTP 服务器: Koa 使用 http.createServer() 方法来创建 HTTP 服务器。通常会看到 Koa 通过 app.callback() 方法将 Koa 应用程序转换为一个可以处理 HTTP 请求的回调函数,http.createServer() 使用这个回调来处理请求。

const Koa = require("koa");
const http = require("http");

const app = new Koa();
const server = http.createServer(app.callback());

app.use((ctx) => {
ctx.type = "application/json";

ctx.body = JSON.stringify({
data: "Hello World!",
});
});

server.listen(8000, () => {
console.log("Koa HTTP Server is running on port 8000");
});

1.3 express http.createServer

使用Expresshttp.createServer 实现 HTTP 服务器: 将 Express 应用程序作为回调传递给 http.createServer()Express 会处理请求并生成响应。

const express = require("express");
const http = require("http");

const app = express();
const server = http.createServer(app);

app.get("/", (req, res) => {
res.send("Hello, Express with HTTP!");
});

server.listen(8000, () => {
console.log("Express HTTP Server is running on port 8000");
});

二、Request


三、Get


四、Post