Node.js使用request库带Bearer Token请求API返回undefined问题求助
res Undefined in Request.js While Postman Works Hey there! Let's break down why your request is returning undefined for the response object, even though Postman works perfectly. Here are the key things to check and fix:
First, always check the error object first
The request.js callback passeserras the first parameter—if there's any error during the request (like network issues, SSL certificate problems, or invalid auth),reswill beundefined. Update your code to log the error first:request({ url: 'https://vdms-dev.clientsolve.com/evoDMDev/api_event.php', headers: { 'Authorization': 'Bearer 71D50F9987529' } }, function(err, res) { if (err) { console.error('Request error:', err); return; } console.log('Response:', res); });Common issues here might be SSL certificate warnings (since it's a dev environment) — if that's the case, add
rejectUnauthorized: falseto your request options (note: only do this in dev, not production!).Match Postman's request details exactly
Double-check that your request matches what you're sending in Postman:- Request method: Postman might be using POST while your code defaults to GET. Add
method: 'POST'(or whatever method Postman uses) to your options. - Additional headers: Postman automatically adds headers like
Content-TypeorUser-Agent—try copying those into your request headers to match. - Request body: If you're sending data in Postman (like form-data or JSON), make sure to include that in your request options (e.g.,
form: {...}orjson: {...}).
- Request method: Postman might be using POST while your code defaults to GET. Add
Verify your auth token is still valid
Even though Postman works, it's possible your code is using a token that's expired or formatted incorrectly. Double-check that theAuthorizationheader string matches exactly what's in Postman (no extra spaces, correct "Bearer " prefix).Consider switching to a maintained library
Keep in mind that request.js is deprecated and no longer maintained. If you run into more issues, switching to libraries likeaxiosornode-fetchmight give you more reliable behavior and better error handling. For example, with axios:axios.get('https://vdms-dev.clientsolve.com/evoDMDev/api_event.php', { headers: { 'Authorization': 'Bearer 71D50F9987529' } }) .then(res => console.log('Response:', res)) .catch(err => console.error('Error:', err));
Start with checking the error object—nine times out of ten, that'll point you right to the problem!
内容的提问来源于stack exchange,提问作者Ratri

