node.js - 将任何路由到单个端点并将特定路由到另一个端点?
问题描述
我想将所有请求路由到一个特定的端点,除了一个,它将转到另一个端点。例如:
//I cannot use express
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const reqUrl = url.parse(req.url, true);
if (reqUrl.pathname == '*' && req.method === 'GET') { //route all to this one
// process
res.end();
}
if (reqUrl.pathname == '/specific' && req.method === 'GET') { //unless the user types in /specific
//process
res.end();
}
}).listen(port, hostname, () => {
console.log(`Server running on port ${port}`);
});
我怎样才能做到这一点?
解决方案
先放你的具体路线,然后放你的一般路线:
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const reqUrl = url.parse(req.url, true);
if (reqUrl.pathname == '/specific' && req.method === 'GET') { //unless the user types in /specific
//process
res.end();
}
else { //route all to this one
// process
res.end();
}
}).listen(port, hostname, () => {
console.log(`Server running on port ${port}`);
});
推荐阅读
- postgresql - 如何修复 PDOException::("SQLSTATE[08006] [7] SCRAM 身份验证需要 libpq 版本 10 或更高版本")
- html - 为什么移动设备上出现键盘时页面会向上移动?
- python - Python是如何求幂的?
- amazon-web-services - 如何正确设置 AWS 入站规则以接受来自外部 REST API 调用的响应
- jquery - 输入文本字段并更改单选按钮组的值
- go - 为什么 calibre 不会读取重新创建的 .epub 文件上的元数据?
- python - 更新 sudo apt 时出现织物问题
- debugging - C# Blazor Webassembly 自定义授权属性不起作用调试
- mysql - mysql语句中的局部变量
- javascript - 为什么我的 Redux 减速器在导入时未定义