Node gets started implementing simple HTTP services
Implement a simple HTTP service (HTML pages, CSS, JSON data, static resources)
Create an HTTP server, http.js
const http = require("http");
const server = http.createServer((request, response) = > {
response.end("Hello World");
});
server.listen(8080.() = > {
console.log("localhost:8080");
});
Copy the code
Type localhost:8080 in your browser to see Hello World
2. Display the home page
2.1 Creating the index. HTML file
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>node-study</title>
</head>
<body>
<h1>Hello Node</h1>
</body>
</html>
Copy the code
2.2 Modifying http.js, return to the home page
- Handling 404 cases
- Server usage
fs.readFile()
Read the index. HTML file data - Processing err
- Return index.html to the client
const http = require("http");
const fs = require("fs");
const server = http.createServer((request, response) = > {
const { url, method } = request;
if (url === "/" && method === "GET") {
// fs.readfile () reads index.html
fs.readFile("index.html".(err, data) = > {
if (err) {
/ / processing err
response.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
response.end("500, server error");
return;
} else {
// Return data to the client
response.statusCode = 200;
response.setHeader("Content-Type"."text/html"); response.end(data); }}); }else {
/ / 404
response.statusCode = 404;
response.setHeader("Content-Type"."text/plain; charset=utf-8");
response.end("404, page not found"); }}); server.listen(8080.() = > {
console.log("localhost:8080");
});
Copy the code
Write a GET interface
Add the following code to the http.js file
else if (url === '/user' && method === "GET") {
response.statusCode = '200'
response.setHeader('Content-Type'."application/json")
response.end(JSON.stringify({name: 'Ming'.age: 20}}))Copy the code
Request interface http://localhost:8080/user
4. Add support for CSS
4.1 the new index. The CSS
h1 {
color: red;
}
Copy the code
4.2 index.html Introduces index.css
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>node-study</title>
<! -- Add CSS -->
<link rel="stylesheet" href="index.css" >
</head>
<body>
<h1>Hello Node</h1>
</body>
</html>
Copy the code
After the above two steps, refresh the page to see 404 returned when requesting the CSS file.
4.3 Modifying http.js to enable clients to obtain CSS files
The Accept attribute in the request header contains the string text/ CSS. Fs.createreadstream () can be used to create a readable stream that reads the index.css file. Then create a pipe to pass the output from the readable stream to Response.
const { url, method, headers } = request;
else if (method === "GET" && headers.accept.indexOf("text/css")! = = -1) {
// Create a readable stream and connect the data through the pipe to the return parameter response
fs.createReadStream("." + url).pipe(response);
}
Copy the code
http.js
const http = require("http");
const fs = require("fs");
const server = http.createServer((request, response) = > {
const { url, method, headers } = request;
if (url === "/" && method === "GET") {
/ / read index. HTML
fs.readFile("index.html".(err, data) = > {
if (err) {
/ / processing err
response.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
response.end("500, server error");
return;
} else {
// Return data to the client
response.statusCode = 200;
response.setHeader("Content-Type"."text/html"); response.end(data); }}); }else if (url === "/user" && method === "GET") {
response.statusCode = "200";
response.setHeader("Content-Type"."application/json");
response.end(JSON.stringify({ name: "Xiao Ming".age: 20 }));
} else if (method === "GET" && headers.accept.indexOf("text/css")! = = -1) {
// Create a readable stream and connect the data through the pipe to the return parameter response
fs.createReadStream("." + url).pipe(response);
} else {
/ / 404
response.statusCode = 404;
response.setHeader("Content-Type"."text/plain; charset=utf-8");
response.end("404, page not found"); }}); server.listen(8080.() = > {
console.log("localhost:8080");
});
Copy the code
Restart the service and refresh the page. You can see that the request for the index. CSS file is successful and the title color becomes red
5. Add JS file support
5.1. Create a JS filehello.js
console.log('Hello World! ')
Copy the code
5.2, modify index.html to introduce hello.js
5.3. Modify http.js so that clients can get files normally
else if (method === "GET" && url.endsWith(".js")) {
// Create a readable stream and connect the data through the pipe to the return parameter response
fs.createReadStream("." + url).pipe(response);
}
Copy the code
6. Add HTTP support for images, audio and video files
else if (method === "GET" && headers.accept.indexOf("image/*")! = = -1) {
// Support image files, create readable streams, and connect data through pipes and return response parameters
fs.createReadStream("." + url).pipe(response);
} else if (method === "GET" && headers.accept === "* / *") {
// Support audio, video, or other files to create readable streams and link data through pipes and return response parameters
fs.createReadStream("." + url).pipe(response);
}
Copy the code
http.js
const http = require("http");
const fs = require("fs");
const server = http.createServer((request, response) = > {
const { url, method, headers } = request;
if (url === "/" && method === "GET") {
/ / read index. HTML
fs.readFile("index.html".(err, data) = > {
if (err) {
/ / processing err
response.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
response.end("500, server error");
return;
} else {
// Return data to the client
response.statusCode = 200;
response.setHeader("Content-Type"."text/html"); response.end(data); }}); }else if (url === "/user" && method === "GET") {
response.statusCode = "200";
response.setHeader("Content-Type"."application/json");
response.end(JSON.stringify({ name: "Xiao Ming".age: 20 }));
} else if (method === "GET" && headers.accept.indexOf("text/css")! = = -1) {
// Support CSS files, create readable streams, and connect data through pipes and return response parameters
fs.createReadStream("." + url).pipe(response);
} else if (method === "GET" && url.endsWith(".js")) {
// Support js files, create readable streams, and connect data through pipes and return response parameters
fs.createReadStream("." + url).pipe(response);
} else if (method === "GET" && headers.accept.indexOf("image/*")! = = -1) {
// Support image files, create readable streams, and connect data through pipes and return response parameters
fs.createReadStream("." + url).pipe(response);
} else if (method === "GET" && headers.accept === "* / *") {
// Support audio, video, or other files to create readable streams and link data through pipes and return response parameters
fs.createReadStream("." + url).pipe(response);
} else {
/ / 404
response.statusCode = 404;
response.setHeader("Content-Type"."text/plain; charset=utf-8");
response.end("404, page not found"); }}); server.listen(8080.() = > {
console.log("localhost:8080");
});
Copy the code
The HTTP service ultimately supports the following file types
Code Address:Github.com/banixing/no…
References:
- Node.js Stream