Skip to content

http

新建文件

// server.mjs

import { createServer } from 'node:http';

const server = createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World');
});

server.listen(80, '127.0.0.1', () => {
  console.log('监听 127.0.0.1:80');
});

运行文件

node server.mjs

浏览器访问 http://127.0.0.1/ ,查看网页。

Ctrl + C 停止服务。

新建文件

// server1.mjs

import { createServer } from 'node:http';

const hostname = '127.0.0.1';
const port = 80;

const server = createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello Human');
});

server.listen(port, hostname, () => {
  console.log(`监听 http://${hostname}:${port}/`);
});

运行文件

node server1.mjs

浏览器访问 http://127.0.0.1/

联系 math@baima.site