how to send image via discord webhook using node-fetch?

Viewed 1047
const fetch = require('node-fetch');
const fs = require('fs')
var data = fs.readFileSync('2.png', 'utf8')
var URL = "apikey";
fetch(URL, {
     "method":"POST",
     "headers": {"Content-Type": "application/json"},
     "body": data
    })
    .then(res=> console.log(res))
    .catch(err => console.error(err));

how can I send images via discord webhook? I have tried the above and it does not work. and there are no proper examples on discord docs.

1 Answers

You are sending a file then your Content-Type should be multipart/form-data.

Change code to

const fetch = require('node-fetch');
const formData = require('form-data');
const fs = require('fs')

const form = new formData();
form.append('file1', fs.createReadStream('./2.png')); // give absolute path if possible

var URL = "XYZ URL";

fetch(URL, {
    'method': 'POST',
    'body': form,
    headers: form.getHeaders()
})
.then(res=> console.log(res))
.catch(err => console.error(err));

See yellow notice in this page of discord's documentations

Related