Home > Web Front-end > JS Tutorial > Create a nodejs server easily (6): respond_node.js

Create a nodejs server easily (6): respond_node.js

WBOY
Release: 2016-05-16 16:25:47
Original
995 people have browsed it

We then modify the server so that the request handler can return some meaningful information.

Let’s see how to implement it:

1. Let the request handler directly return (return()) the information they want to display to the user through the onRequest function.
2. Let’s start by having the request handler return the information that needs to be displayed in the browser.

We need to modify requestHandler.js to the following form:

Copy code The code is as follows:

function start() {
console.log("Request handler 'start' was called.");
Return "Hello Start";
}
function upload() {
console.log("Request handler 'upload' was called.");
Return "Hello Upload";
}
exports.start = start;
exports.upload = upload;

Similarly, request routing needs to return to the server the information returned to it by the request handler.
Therefore, we need to modify router.js to the following form:

Copy code The code is as follows:

function route(handle, pathname) {
console.log("About to route a request for " pathname);
if (typeof handle[pathname] === 'function') {
return handle[pathname]();
} else {
console.log("No request handler found for " pathname);
return "404 Not found";
}
}

exports.route=route;

As shown in the above code, when the request cannot be routed, we also return some related error information.
Finally, we need to refactor our server.js so that it responds to the browser with the content returned by the request handler via the request route, like this:

Copy code The code is as follows:

var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " pathname " received.");
response.writeHead(200, {"Content-Type": "text/plain"});
var content = route(handle, pathname);
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start=start;

If we run the refactored application:

Request http://localhost:8888/start, the browser will output "Hello Start",
Requesting http://localhost:8888/upload will output "Hello Upload",
And requesting http://localhost:8888/foo will output "404 Not found".

This feels good. In the next section we will learn about a concept: blocking operations.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template