- 读取HTML
1.编辑index.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> <style> body{ background: skyblue; color: #fff; padding: 30px; } h1{ font-size: 48px; letter-spacing: 2px; text-align: center; } p{ font-size: 16px; text-align: center; } </style> </head> <body> <h1>Welcome to NodeJS</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur eius quae quaerat quisquam similique. Ad inventore nihil quia sequi, tempora
totam voluptates? Accusantium ad animi corporis maxime nam quod vero.</p> </body> </html>2.引入服务器模块,并读取文件
var http = require('http'); // 1.引入文件模块 var fs = require('fs'); //搭建服务器 var server = http.createServer(function (req,res) { res.writeHead(200,{"Content-type":"text/html"}); //注意:读取html文件时,要把响应头的类型改为text/html var myReadStream = fs.createReadStream('index.html', 'utf8'); //读取的文件 myReadStream.pipe(res); }); server.listen(3033,'127.0.0.1'); console.log("OK");
3.运行服务器,在网页中打开
- 读取JSON
1.编辑person.json文件
{ "name":"Jona", "age":21, "Job":"Monkey" }
2.引入服务器模块,并读取文件
var http = require("http"); var fs = require("fs"); //创建服务器 var server = http.createServer(function (req,res) { console.log('客户端向服务器发送请求' + req.url); if(req.url !=='/favicon.ico') res.writeHead(200,{"Content-type":"application/json"}); var myReadStream = fs.createReadStream('person.json', "utf8"); myReadStream.pipe(res); }); server.listen(4444,'127.0.0.1'); console.log("你是SB吗");
3.在浏览器打开文件
Node入门--10-->HTML&JSON
最新推荐文章于 2023-12-03 01:02:39 发布