一、nodejs网络模块的第一个程序
代码语言:javascript复制const http = require('http');
const hostName = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('hello world');
})
server.listen(port, hostName, () => {
console.log(`Server running at http://${hostName}:${port}`);
})
二、获取服务路由地址
准备三个文件
server 文件夹 --index.js --router.js --first-serve.js
代码语言:javascript复制// index.js
const server = require("./first-serve");
const router = require("./router");
server.start(router.route);
代码语言:javascript复制// router.js
const route = (pathName) => {
console.log("About to route a request for" pathName)
}
exports.route = route;
代码语言:javascript复制// first-serve.js
const http = require('http');
const url = require('url');
const hostName = '127.0.0.1';
const port = 3000;
function start(route) {
function onRequest(request, response) {
let pathName = url.parse(request.url).pathname;
console.log('Request for' pathName " received");
route(pathName);
response.writeHead(200, { "Content-Type": "text/plain" });
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(port, hostName);
console.log("Serve has started.")
}
exports.start = start;
用 url.parse(request.url).pathname
获取到路由地址
用node index.js
启动服务,可以看到控制台打印:
// Serve has started.
然后在浏览器输入 http://127.0.0.1:3000/user 访问,我们可以看到打印以下信息
代码语言:javascript复制// Request for/user received
// About to route a request for/user
// Request for/favicon.ico received
// About to route a request for/favicon.ico
写在最后
我是 AndyHu,目前暂时是一枚前端搬砖工程师。
文中如有错误,欢迎在评论区指正,如果这篇文章帮到了你,欢迎点赞和关注呀