I keep getting a connection reset error when trying to submit form data to HubSpot using Node.js. The same logic works perfectly in PHP but fails in my Node.js application. I tested this on both local development and production environments with the same result.
app.post('/submit-form', (req, res) => {
const https = require('https');
const querystring = require('querystring');
const PORTAL_ID = "YOUR_PORTAL_ID";
const FORM_ID = "YOUR_FORM_GUID";
const formData = querystring.stringify({
'email': "[email protected]",
'name': "John Doe",
'phone_number': "555-123-4567",
'comments': "Test message from Node.js",
'hs_context': JSON.stringify({
"hutk": '',
"ipAddress": req.ip || req.connection.remoteAddress,
"pageUrl": "/contact-us",
"pageName": "Contact Form"
})
});
const requestOptions = {
hostname: 'forms.hubspot.com',
path: `/uploads/form/v2/${PORTAL_ID}/${FORM_ID}`,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(formData)
}
};
const req = https.request(requestOptions, (response) => {
console.log(`Response status: ${response.statusCode}`);
response.on('data', (data) => {
console.log(`Response data: ${data}`);
});
});
req.on('error', (error) => {
console.log(`Request failed: ${error.message}`);
});
req.write(formData);
req.end();
res.json({"status": "Form submission processed"});
});
The error I get is: Request failed: Error: read ECONNRESET
What could be causing this connection issue in Node.js when PHP works fine with the same API endpoint?