Node.js中使用request.js调用REST API时如何传递请求参数?
Hey there! Let's break down how to send parameters like project and prefix when using request.js to call a REST API (specifically the Google Cloud Storage buckets list endpoint you mentioned) in Node.js.
First, install request.js
Before diving in, make sure you've got the package set up in your project:
npm install request
Quick note:
requestis officially deprecated now, so for new projects, you might want to look into alternatives likeaxiosornode-fetch. But since you asked aboutrequest.js, we'll focus on that here.
Two ways to pass your parameters
There are two main approaches to include those query parameters in your request—one is manual, the other is the library's built-in (and recommended) method.
1. Manual URL concatenation (not ideal)
You can append parameters directly to the API URL string, but this gets messy if your parameters have special characters (you'd have to handle URL encoding yourself). Here's what that looks like:
const request = require('request'); // Define your parameters const projectId = 'your-gcp-project-id'; const prefix = 'my-bucket-folder-prefix/'; // Build the full URL with query params const apiUrl = `https://storage.googleapis.com/storage/v1/b?project=${projectId}&prefix=${prefix}`; // Send the GET request request.get(apiUrl, (error, response, body) => { if (error) { return console.error('Oops, request failed:', error); } // Parse and work with the response const bucketData = JSON.parse(body); console.log('Buckets matching your prefix:', bucketData.items); });
2. Use the qs option (Recommended)
The request library has a qs (query string) option that automatically handles URL encoding and formats your parameters correctly. This is way cleaner and avoids mistakes from manual string building:
const request = require('request'); // Set up your request options const reqOptions = { url: 'https://storage.googleapis.com/storage/v1/b', method: 'GET', // Your parameters live here—super straightforward qs: { project: 'your-gcp-project-id', prefix: 'my-bucket-folder-prefix/', // Add any other supported params here, like: maxResults: 15, fields: 'items(name,size,timeCreated)' }, // Optional: Add authentication if the API requires it (most GCP APIs do!) headers: { 'Authorization': 'Bearer YOUR_OAUTH2_ACCESS_TOKEN' } }; // Run the request request(reqOptions, (error, response, body) => { if (error) { return console.error('Request error:', error); } // Check if we got a successful response if (response.statusCode === 200) { const buckets = JSON.parse(body); console.log('Fetched buckets:', buckets); } else { console.error('API returned an error:', response.statusCode, body); } });
A few important notes
- Authentication: For Google Cloud APIs, you'll need to authenticate your request. You can use an API key (add
key: 'YOUR_API_KEY'to theqsobject) or an OAuth2 access token in theAuthorizationheader. - Parameter rules: Make sure your parameters match the API's requirements—for example,
projectneeds to be a valid GCP project ID, andprefixshould follow bucket naming conventions. - Error handling: Always handle network errors and non-200 status codes, like in the examples above. It saves you from head-scratching later!
内容的提问来源于stack exchange,提问作者vdenotaris

