Nodejs create web server

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/fukaiit/article/details/102756238

Sometimes you need to create a simple web server access at the test page. I had previously been to create a java web project, a bit of trouble.
Nodejs can be used to create a simple web server, access to some static pages, such as: iframe issues related to time, direct file protocol to open static files will have problems in cross-domain test requires a minimalist web server.
server.js

var http = require('http');
var fs = require('fs');
var url = require('url');

http.createServer(function(req, res) {
    //解析出请求的文件路径
    var pathname = url.parse(req.url).pathname;
    console.log('接收到请求,请求的是:' + pathname);
    //从文件系统中读取请求的文件内容
    fs.readFile(pathname.substr(1), function(err, data) {
        if (err) {
            console.error(err);
            res.writeHead(404, { 'Content-Type': 'text/html' }); //404
        } else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.write(data.toString());
        }
        res.end();
    });
}).listen(8888);

console.log('Server running at port 8888. 请访问:http://127.0.0.1:8888/index.html');

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    这是我将要请求的页面,浏览器显示我就算成功了。
</body>
</html>

Start:

node server.js

Resource Links: https://download.csdn.net/download/fukaiit/11927768

Guess you like

Origin blog.csdn.net/fukaiit/article/details/102756238