2019-03-08 14:07:30 1131浏览
今天扣丁学堂HTML5培训老师给大家介绍一下关于零基础学习Node.js搭建API服务器的详解,希望学习HTML5开发有所帮助,下面我们一起来看一下吧。
// index.js
// 通过require获取两个node内置模块
const http = require('http');
const nUrl = require('url');
// '127.0.0.1'表明只有本机可访问,'0.0.0.0'表示所有人可访问
const hostname = '127.0.0.1';
const port = 3000;
// 通过http.createServer获取一个server实例
// 其中(req, res) => {},在服务器每次接收到请求时都会被执行
const server = http.createServer((req, res) => {
let method = req.method; // 客户端请求方法
let url = nUrl.parse(req.url); // 将请求url字符串转换为node的url对象
// 如果客户端GET请求'/',会执行这个分支里面的逻辑
if (method === 'GET' && url.pathname === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
return;
}
// 如果客户端GET请求'/api/user',会执行这个分支里面的逻辑
if (method === 'GET' && url.pathname === '/api/user') {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
code: 0,
msg: '',
result: {
username: 'shasharoman'
}
}));
return;
}
// 没有匹配其他分支的话,执行以下逻辑
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not Found');
});
// server开始监听,等待请求到来
server.listen(port, hostname, () => {
console.log(`Server running at <a href="http://${hostname}:${port}/`);" rel="external nofollow">http://${hostname}:${port}/`);
</a>});
// config.js
exports = module.exports = {
hostname: '127.0.0.1',
port: '3000'
};
// route.js
exports = module.exports = [{
method: 'GET',
path: '/api/user',
impl: 'account.userById'
}, {
method: 'POST',
path: '/api/user',
impl: 'account.createUser'
}];
// controller/account.js
exports.userById = userById;
exports.createUser = createUser;
function userById(req, res) {
res.end('waiting for impl.');
}
function createUser(req, res) {
res.end('waiting for impl.');
}
// controller/index.js
exports.account = require('./account');
// index.js
const http = require('http');
const nUrl = require('url');
const config = require('./config');
const controller = require('./controller');
const route = require('./route').map(item => {
console.log(`route ${item.method}:${item.path}`);
let tuple = item.impl.split('.');
item.impl = controller[tuple[0]][tuple[1]];
return item;
});
const server = http.createServer((req, res) => {
let method = req.method;
let url = nUrl.parse(req.url);
let matchRoute = route.find(item => {
return item.method === method && item.path === url.pathname;
});
if (matchRoute) {
matchRoute.impl(req, res);
return;
}
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not Found');
});
server.listen(config.port, config.hostname, () => {
console.log(`Server running at <a href="http://${config.hostname}:${config.port}/`);" rel="external nofollow">http://${config.hostname}:${config.port}/`);
</a>});
【关注微信公众号获取更多学习资料】