如何使用node-fetch通过Discord Webhook发送图片?现有代码无法运行求解决方案
How to Send Images via Discord Webhook with Node.js
Hey there! Let's fix your code step by step—your current approach has a few key issues that are preventing the image from being sent correctly to Discord's webhook.
What's Wrong with Your Current Code?
- Incorrect Body Format: You're using
JSON.stringify()for the body, but Discord expectsmultipart/form-datawhen uploading files. JSON can't handle file streams, so this won't work. - Manual Header Mistakes: You're setting
Content-TypeandContent-Dispositionheaders manually, but these are automatically handled when using aFormDataobject. Manually setting them can lead to mismatched boundaries or incorrect formatting. - Invalid File Size Check:
fs.createReadStream()doesn't have asizeproperty. Trying to accessdata.sizewill give youundefined, which breaks theContent-lengthheader. - Missing Webhook URL: Your
URLvariable is set to "apikey"—you need to replace this with your actual Discord webhook URL (looks likehttps://discord.com/api/webhooks/...).
The Corrected Solution
To send files via Discord webhook, you need to use the form-data package (since Node.js doesn't have a built-in FormData for CommonJS) along with node-fetch. Here's how to do it:
First, install the required packages if you haven't already:
npm install node-fetch@2 form-data
Then use this code:
const fetch = require('node-fetch'); const fs = require('fs'); const FormData = require('form-data'); // Replace this with your actual Discord webhook URL const WEBHOOK_URL = "https://discord.com/api/webhooks/your-webhook-id/your-webhook-token"; // Create a new FormData instance const form = new FormData(); // Append the file to the form form.append('file', fs.createReadStream('2.png'), { filename: '2.png' }); // Optional: Add a message to send along with the image form.append('content', 'Check out this image!'); // Send the request fetch(WEBHOOK_URL, { method: 'POST', body: form, // Let form-data handle the headers automatically headers: form.getHeaders() }) .then(res => { if (res.ok) { console.log('Image sent successfully!'); } else { console.log(`Failed to send image. Status: ${res.status}`); return res.text(); } }) .then(text => text && console.log('Response:', text)) .catch(err => console.error('Error:', err));
Key Notes:
- FormData Handling: The
form-datapackage handles all the multipart formatting, including setting the correctContent-Typeheader with a boundary string. Usingform.getHeaders()ensures these headers are set properly. - File Appending: When appending the file, you can specify the filename (third argument) to tell Discord what to name the file.
- Optional Content: You can add additional fields like
content(message text) orusername(override the webhook's default username) by appending them to the FormData object. - Error Handling: The code checks if the response is okay and logs any errors or status messages to help debug if something goes wrong.
This should resolve your issue and send the image to your Discord webhook successfully.
内容的提问来源于stack exchange,提问作者hrenacher228




