- Building Google Cloud Platform Solutions
- Ted Hunter Steven Porter Legorie Rajan PS
- 298字
- 2025-04-04 14:47:42
Processing HTTP requests
As mentioned, functions using the HTTP trigger are defined as handlers for the popular Express.js framework. The provided req and res parameters conform to Express standards. Cloud Functions applies basic middleware to aid in processing requests, namely in parsing request bodies based on their Content-Type header. The primary methods for providing data in a request are via the request body and query parameters. Request bodies are parsed into JavaScript objects available at req.body, while query parameters are available as a JavaScript object in req.query.
For example, if a function triggered as an HTTP POST with a request body of { "color": "blue" }, the color property can be retrieved as req.body.color. Likewise, for a function invoked via /functionName?color=blue, the color property can be retrieved as req.query.color.
Once a function has completed processing the request, it should return a response via the res.send() function. By default, this will result in an HTTP 200 status code. The response status can be modified before sending via res.status(<STATUS>).send(). A response body can be provided by passing it through the send function, for example res.send({ color: ‘red' }).
Because HTTP functions leverage the Express.js library, it is possible to have a single function handle entire classes of API operations. This can be done by leveraging Express routers, or simply analyzing the incoming request for things such as path parameters and HTTP methods. Taken to the extreme, this approach can be used to drive entire APIs or web applications. It is up to the developer to determine which approach best fits their use case.