Node.js request.post请求失效求助:向温控器接口发送数值
Hey there! Let's troubleshoot why your POST request works in Advanced REST Client but not in your app's tstatRequest function. I've run into similar issues before, so here are the most likely fixes:
Common Issues & Fixes
Missing or Incorrect
Content-TypeHeader
Advanced REST Client automatically sets the right header when you input plain text, but therequestlibrary doesn't do this by default. Your server is probably expectingtext/plainto parse the "2000" payload correctly.Incorrect Payload Format
Make sure you're sending the payload as a string ('2000') instead of a number (2000). Servers expect plain text to be a string, not a numeric value.Lack of Error Logging
Without error handling, you can't tell if the issue is a network problem, server error, or malformed request. Adding logs will help you pinpoint exactly what's going wrong.
Corrected Code Example
Here's a revised version of your function with all these fixes included:
const request = require('request'); exports.tstatRequest = function() { const targetUrl = 'http://192.168.0.100/control/thermostat.cgi?param=thermostat_manualsetpoint'; const payload = '2000'; // Ensure this is a string request.post({ url: targetUrl, body: payload, headers: { 'Content-Type': 'text/plain' // Critical: Match what ARC sends } }, (error, response, body) => { // Add error logging to diagnose issues if (error) { console.error('Request failed with error:', error); return; } // Check server response status console.log('Server status code:', response.statusCode); console.log('Server response body:', body); }); };
Alternative with Axios (Easier Error Handling)
If you're open to switching libraries, Axios makes this even simpler with built-in promise support:
const axios = require('axios'); exports.tstatRequest = async function() { try { const targetUrl = 'http://192.168.0.100/control/thermostat.cgi?param=thermostat_manualsetpoint'; const response = await axios.post(targetUrl, '2000', { headers: { 'Content-Type': 'text/plain' } }); console.log('Success! Status:', response.status); console.log('Response:', response.data); } catch (error) { console.error('Request failed:', error.response ? error.response.data : error.message); } };
Next Steps
After updating your code, check your console for logs:
- If you see a network error (like
EHOSTUNREACH), verify your app can reach the 192.168.0.100 server (check firewall, network access). - If you get a 4xx status code, double-check the URL parameters and payload format.
- If you get a 5xx status code, the issue might be on the server side (though ARC working suggests this is less likely).
内容的提问来源于stack exchange,提问作者Kylix

