Home > Web Front-end > JS Tutorial > body text

How to make node.js interface

php中世界最好的语言
Release: 2018-06-04 10:48:55
Original
2607 people have browsed it

This time I will show you how to make a node.js interface and what are the precautions for making a node.js interface. The following is a practical case. Let’s take a look. .

Recently I have to write a tool interface to integrate the functions of the project Attributes to facilitate editing by people in other departments, somewhat similar to the backend. There will be some data interaction. So I learned about the node.js backend.

The source code is as follows:

// filename:myServer.js
// a simple http server
var
 fs = require('fs'),
 url = require('url'),
 path = require('path'),
 http = require('http');
//从命令行参数获取root目录,默认是当前目录
var root = path.resolve(process.argv[2] || '.');
console.log('Static root dir: ' + root);
//创建服务器
var server = http.createServer(function (request, response) {
 //获取URL的路径
 var pathname = url.parse(request.url).pathname,
 //获取对应的本地文件的路径
 filepath = path.join(root, pathname);
 //获取文件状态
 fs.stat(filepath, function (err, stats) {
 if (!err && stats.isFile()) {
  console.log('200 ' + request.url);
  //发送响应
  response.writeHead(200);
  //将文件流导向response
  fs.createReadStream(filepath).pipe(response);
 } else {
  console.log('404 ' + request.url);
  response.writeHead(404);
  response.end('404 Not Found');
 }
 });
});
server.listen(8081);
console.log('Server is running at http://127.0.0.1:8081/');
Copy after login

The directory structure of this project is as follows:

After the js and html pages are written as usual, execute the cnd command:

##The final effect is as follows:

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to operate Vue to remove the # sign in the path

How to use vue to click on the blank space Hidden div implementation

The above is the detailed content of How to make node.js interface. For more information, please follow other related articles on the PHP Chinese website!

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