You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何使用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?

  1. Incorrect Body Format: You're using JSON.stringify() for the body, but Discord expects multipart/form-data when uploading files. JSON can't handle file streams, so this won't work.
  2. Manual Header Mistakes: You're setting Content-Type and Content-Disposition headers manually, but these are automatically handled when using a FormData object. Manually setting them can lead to mismatched boundaries or incorrect formatting.
  3. Invalid File Size Check: fs.createReadStream() doesn't have a size property. Trying to access data.size will give you undefined, which breaks the Content-length header.
  4. Missing Webhook URL: Your URL variable is set to "apikey"—you need to replace this with your actual Discord webhook URL (looks like https://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-data package handles all the multipart formatting, including setting the correct Content-Type header with a boundary string. Using form.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) or username (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

火山引擎 最新活动