如何将带文件上传的CURL请求转换为Node.js代码?
Fixing Node.js fetch File Upload to Veracode API (Converted from cURL)
Let's work through the issues with your code—there are a few small but critical mistakes that are keeping your file upload from working, even though your auth flow works for other endpoints.
First, let's recap your original cURL command to align our fixes:
curl --compressed -u $username:$password https://analysiscenter.veracode.com/api/5.0/uploadfile.do -F "app_id=1" -F "file=@package.zip"
Key Issues in Your Current Code
- Mismatched API Version: Your cURL uses
api/5.0/but your code callsapi/4.0/—Veracode's API versions have strict compatibility rules, so this alone could break the request. - FormData Variable Mix-Up: You define
uploadFileFormbut try to get the boundary fromform(which doesn't exist). This would throw an error or generate an invalid boundary. - Typos in Fetch Options: You used
headerinstead ofheaders(plural) in the fetch config—this means your custom auth header isn't actually being sent. - Missing Node.js FormData Dependency: Node.js doesn't have a native
FormDataimplementation like browsers do; you need theform-datanpm package to handle multipart uploads correctly. - Unspecified File Metadata: Your file stream is missing a filename/content-type hint, which might cause Veracode's API to reject the upload.
Fixed Code
First, install the required dependencies:
npm install node-fetch form-data
Then use this corrected code:
const fetch = require("node-fetch"); const FormData = require("form-data"); // Use the npm package for Node.js const fs = require("fs"); // Replace with your actual credentials const myUsername = "your-username"; const myPassword = "your-password"; // Generate Basic Auth token (same working flow you used for other APIs) const authToken = Buffer.from(`${myUsername}:${myPassword}`).toString("base64"); // Build the multipart form data const uploadForm = new FormData(); uploadForm.append("app_id", "1"); // Add the file stream with explicit filename/content-type (matches cURL's @package.zip) uploadForm.append("file", fs.createReadStream("package.zip"), { filename: "package.zip", contentType: "application/zip" }); // Combine FormData's auto-generated headers with your auth header const requestHeaders = { ...uploadForm.getHeaders(), // Auto-includes correct Content-Type + boundary Authorization: `Basic ${authToken}` }; // Match the API version from cURL, add --compressed equivalent fetch("https://analysiscenter.veracode.com/api/5.0/uploadfile.do", { method: "POST", headers: requestHeaders, // Fixed the plural "headers" typo body: uploadForm, compress: true // Matches cURL's --compressed flag }) .then(res => res.text()) .then(body => console.log("API Response:", body)) .catch(err => console.error("Upload failed:", err));
Why This Works
- API Version Alignment: Using
api/5.0/matches your original cURL, ensuring compatibility with Veracode's upload endpoint. - Proper FormData Handling: The
form-datapackage automatically manages the multipart boundary and content structure, so you don't have to manually construct theContent-Typeheader (which is easy to mess up). - Fixed Header Spelling:
headers(plural) ensures your auth token and form data headers are all sent correctly. - Explicit File Metadata: Specifying the filename and content-type helps Veracode's API recognize the file format, just like the
@package.zipsyntax in cURL. - Compression Support: The
compress: trueoption tells the server we accept compressed responses, matching the--compressedflag in your cURL.
Quick Debug Tips If It Still Fails
- Log the
requestHeadersto confirm theAuthorizationandContent-Typeheaders are correctly formatted. - Check for corporate proxy issues—many enterprise environments require proxy configuration to access Veracode's API.
- Catch and log full error details (not just the message) to see if it's a network issue or a specific error from Veracode's API.
内容的提问来源于stack exchange,提问作者Antoine Drouhin
相关产品推荐
相关产品推荐

