Blog
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)

HiuZing

🍑
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)
  • 前端面试题

  • JavaScript

  • Vue2

  • port

  • CSS

  • Node.js

    • nvm

    • Node.js实例

    • Pm2

    • npm

    • 教程

      • Node.js-回调函数
      • Node.js-事件循环
      • Node.js-Buffer
      • Node.js-Stream
      • Node.js-函数
      • Node.js-模块系统
      • Node.js-路由
      • Node.js-全局对象
      • Node.js-常用工具
      • Node.js-文件系统
  • JavaScript优化

  • uniapp

  • Mini Program

  • TypeScript

  • 面向对象编程

  • UI组件

  • Plugin

  • Vue3

  • 性能优化

  • Axios

  • 状态管理

  • React

  • Mock

  • Icon

  • Template

  • 构建工具

  • 项目规范配置

  • Taro

  • SVG

  • React Native

  • 前端
  • Node.js
  • 教程
HiuZing
2023-02-17

Node.js-路由

# Node.js 路由

解析以下URL,我们需要 Node.JS 模块,它们分别是 url 和 querystring 模块

http://localhost:8888/start?foo=bar&hello=world
1

数据如下:

start:url.parse(string).pathname

foo=bar&hello=world:url.parse(string).query

bar:querystring.parse(queryString)["foo"]

world:querystring.parse(queryString)["hello"]

创建server.js 文件

onRequest() 函数加上一些逻辑,用来找出浏览器请求的 URL 路径

var http = require("http");
var url = require("url");
 
function start(route) {
  function onRequest(request, response) {
    var 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(8888);
  console.log("Server has started.");
}
 
exports.start = start;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

创建 router.js 的文件

function route(pathname) {
  console.log("About to route a request for " + pathname);
}
 
exports.route = route;
1
2
3
4
5

相应扩展 index.js,使得路由函数可以被注入到服务器中

var server = require("./server");
var router = require("./router");
 
server.start(router.route);
1
2
3
4
上次更新: 2024/08/14, 04:14:33
Node.js-模块系统
Node.js-全局对象

← Node.js-模块系统 Node.js-全局对象→

最近更新
01
React Native 使用SVG
08-13
02
Docker基础命令
08-04
03
算数逻辑单元
07-30
更多文章>
Theme by Vdoing | Copyright © 2021-2024 WeiXiaojing | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式