我想发送所有以" / robot"开头的路径使用ESP8266WebServer.h到某个处理程序。我尝试了一些变化:
server.on ( "/robot", handleDirection );
server.on ( "/robot/", handleDirection );
server.on ( "/robot/*", handleDirection );
但在每种情况下,它只会侦听确切的路径(包括该路径的*)。
此库是否不支持通配符路径?或者我错过了怎么做?
答案 0 :(得分:2)
我在一个例子中找到了一个解决方法。我可以让我未找到的处理程序直接检查uri并处理这种情况。 IE,
void handleDirection(String path) {
int index = path.lastIndexOf('/');
String direction = path.substring(index, path.length());
Serial.println(direction);
}
void handleNotFound() {
String path = server.uri();
int index = path.indexOf("/robot");
if (index >= 0) {
handleDirection(path);
}
returnNotFound();
}
void setup() {
[...]
server.onNotFound ( handleNotFound );
[...]
}
现在有效。如果其他人找到正确的方法,我会留下未回答的问题。
答案 1 :(得分:1)
这很容易用面向对象的方式
class MyHandler : public RequestHandler {
bool canHandle(HTTPMethod method, String uri) {
return uri.startsWith( "/robot" );
}
bool handle(ESP8266WebServer& server, HTTPMethod requestMethod, String requestUri) {
doRobot( requestUri );
server.send(200, "text/plain", "Yes!!");
return true;
}
} myHandler;
...
server.addHandler( &myHandler );
...
答案 2 :(得分:1)
您可以通过使用正则表达式执行以下操作来实现此目的:
#include <uri/UriRegex.h>
web_server.on(UriRegex("/home/([0-9]+)/first"), HTTP_GET, [&]() {
web_server.send(200, "text/plain", "Hello from first! URL arg: " + web_server.pathArg(0));
});
web_server.on(UriRegex("/home/([0-9]+)/second"), HTTP_GET, [&]() {
web_server.send(200, "text/plain", "Hello from second! URL arg: " + web_server.pathArg(0));
});
然后尝试像这样调用 URL:
http://<IP ADDRESS>/home/123/first
那么您应该会在浏览器中看到以下内容!
<块引用>首先你好!网址参数:123
请注意,每个 RegEx group 都对应一个 pathArg
。
查看 Arduino 框架的 ESP 源代码后,根据 GitHub 上的以下 file、pull request 和 issue,在 this 注释中指出您有三个选择:
<块引用>选项 1:@Bmooij 的提议,在 #5214 中为通配符和 pathArgs 自定义“{}”
选项 2:glob 样式模式匹配,超级标准,在#5467 中的大多数 shell 中使用
选项 3:正则表达式模式匹配,这也是超级标准,虽然有点复杂。