技术咨询:CoffeeScript Hubot中robot.router与robot.http的区别
robot.router and robot.http in Hubot Great question—these two tools look similar at first glance because they both use HTTP verbs, but they serve completely different roles in your Hubot app. Let’s break it down clearly:
What is robot.router?
robot.router is Hubot’s way of turning your bot into an HTTP server (it’s built on top of Express, as you suspected). Its job is to receive incoming HTTP requests from external systems and respond to them.
- Use cases:
- Setting up webhooks to listen for events from third-party services (like GitHub repo pushes, Slack events, or form submissions)
- Exposing custom API endpoints so other tools can trigger Hubot actions (e.g., a CI server calling
/hubot/deployto start a deployment)
- Example:
# When someone sends a GET request to /hubot/health, return a status message robot.router.get '/hubot/health', (req, res) -> res.send 'Hubot is up and running!'
What is robot.http?
robot.http is Hubot’s built-in HTTP client—it lets your bot send outgoing HTTP requests to external APIs or services. It’s a wrapper around common HTTP client logic, making it easier to handle requests/responses without extra dependencies.
- Use cases:
- Fetching data from external APIs (like pulling weather info, GitHub repo stats, or Jira ticket details)
- Sending data to third-party services (like posting a message to a Slack channel via API, or updating a record in a CRM)
- Example:
# Fetch weather data from an API and log the result robot.http('https://api.example.com/weather?city=Boston') .get() (err, res, body) -> if err robot.logger.error "Failed to fetch weather: #{err}" else robot.logger.info "Boston weather: #{body}"
Key Semantic Difference
The core distinction boils down to direction:
robot.router: Inbound traffic—your Hubot is the server receiving requests.robot.http: Outbound traffic—your Hubot is the client sending requests.
Even though they both use verbs like GET/PUT/DELETE, those verbs mean opposite things here:
- With
router.get, you’re saying "when someone sends a GET request to this URL, run this code". - With
http.get, you’re saying "send a GET request to this external URL, then handle the response".
It’s totally normal to use both in the same app—for example, your Hubot might listen for a GitHub webhook via router to get notified of new PRs, then use http to call the GitHub API to fetch more details about that PR and post them to Slack.
内容的提问来源于stack exchange,提问作者Thom

