This is the second day of my participation in the August Text Challenge.More challenges in August
Basic concepts — Domain name,IP
, port, URL
- When I surf the Internet at ordinary times, I willThe domain nameconvert
ip
To access the specified web server (such as the local domain name islocalhost
And its correspondingIP
is127.0.0.1
). - The port is the communication between the computer and the outside world, used to distinguish the different services provided by the server.
- What we usually refer to as a web page address is a URL (consisting of:
Transport protocol :// Server IP address or domain name: port/resource location identifier
).http
It’s a hypertext transfer protocol that provides a way to publish and receiveHTML
Page method.
Creating a Web Server
Infrastructure:
// References the system module
const http = require('http');
// Create web server
const app = http.createServer();
// Listen for the client to send the request
app.on('request'.(req, res) = > {
res.end('<h1>hello</h1>'); // Response content
})
// Listen on port 3000
app.listen(3000);
console.log('Server started successfully, listening on port 3000');
Copy the code
At this time, use Nodemon app.js to start the server, and then open localhost:3000 to see the level-1 title Hello.
If you want to render a file, you can use the FS module. When the requested address corresponds to a URL, render the file with fs.readfile; Set up a request header that writes the contents of the file to the page and responds to the browser.
let path = req.url;
let newPath = path.split('.');
if (newPath == "html") {
fs.readFile(`01_First/src/${newPath}`, "utf-8", function (err, data) {
res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
res.write(data);
res.end();
})
}
Copy the code
For different request URLS, set different request headers to return corresponding files to the browser;
1. The HTTP protocol
Hypertext Transfer Protocol (HYPERtext Transfer Protocol), which works on the client-server architecture, is the standard for both client-side and server-side requests and responses.
-
Request Method
- GET request data
- POST Sends data
-
Request URL
- Different messages can be returned depending on the address requested (see the console’s
network
)
- Different messages can be returned depending on the address requested (see the console’s
app.on('request'.(req, res) = > {
req.headers // Get the request packet
req.url // Get the requested address
req.method // Get the request method
})
Copy the code
The HTTP status code returns 200 indicating that the request succeeded, 404 indicating that the resource was not found, 500 indicating that the server side error, and 400 indicating that the client side request has a syntax error.
Content type :(1) text/ HTML; (2) text/CSS; (3) application/javascript; (4) image/jpeg. (5) Application /json; WriteHead (400, {‘content-type’: ‘text/ HTML ‘; Charset = UTf8}) to write the status code and return type. (Response: res.end())
2. Request parameters
Get request parameters: The parameters are placed in the browser address bar, for example: http://localhost:3000/? Name =mannqo. With get request parameters, you can also see the request parameters in res.url. Two methods are provided here.
First, the way of string interception, and node.js built-in module QueryString to deal with, first use the way of string interception to extract parameters, and then convert them into objects. Spilt means? Cut the string into a 2-element array and extract [1] (the corresponding array element for the parameter).
Second, fetch the parameter values using another node.js built-in module URL
// Method 1:
const querystring = require('querystring');console.log(querystring.parse(req.url.split('? ') [1])); // key=value
// Method 2:
const url = require('url');
let params = url.parse(req.url, true).query;
console.log(params.name); // Retrieve parameter values
Copy the code
Post request parameters: The Post parameters are received as an event. The Data event is fired when the request parameters are delivered, and the End event is fired when the parameters are delivered. To respond to the client after receiving an argument is res.end(). The passed argument is separated by &, and we can use queryString to process the argument as an object.
app.on('request'.(req, res) = > {
let postParams = ' '; // Receive parameters
req.on('data'.(params) = > {
postParams += params;
})
req.on('end'.() = > {
console.log(postParams);
})
res.end('ok');
})
Copy the code
After submitting the parameters with POST, the submitted parameters are visible in the console’s Network.
<form method="POST" action="http://localhost:3000">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
Copy the code
Static and dynamic resources
- Static resources: Resources that the server can respond to the client without processing are static resources, for example
css
,JavaScript
,image
File. A file that the browser can run directly. - Dynamic resources: the same request address gets different response parameters, such as dynamic resources
http://localhost/index?id=1
andhttp://localhost/index?id=2
The request address is the same, but the response from the server is different.
Obtaining dynamic Resources
- You can create a
public
In the folder we want to passlocalhost
In browser The page accessed in the browser - Gets the user’s request path
- Convert the user’s request path to the actual server disk path (
__dirname
: Get the absolute path to the current file. - Read the file and render the contents of the read file to the page
app.on('request'.(req, res) = > {
let pathname = url.parse(req.url).pathname;
pathname = pathname == '/' ? '/canvas.html' : pathname;
let realPath = path.join(__dirname + '/public/' + pathname);
fs.readFile(realPath, (err, result) = > {
if(err ! =null) {
res.writeHead(404, {'content-type': 'text.html'})
console.log('File read failed'); // Chinese characters are garbled, so utF is specified
return; } res.end(result); })}Copy the code
File hierarchy
After this process, files stored in the public folder can be found in the server through the suffix of the file name. Another thing to note here is that sometimes the content-type will affect the rendering of the page. For example, if the response message contains Chinese characters, it will be garbled, so we will use ‘content-type’: ‘text-.html’ to set the response type. One of the modules that’s handy for us is MIME, and with the introduction of the mine module it can help us change the Content-Type to the corresponding file type.
let type = mime.getType(realPath);
res.writeHead(200, {
'content-type': type
})
Copy the code