Home > other >  how to receive files using nodejs express
how to receive files using nodejs express

Time:02-23

im trying to make my own api and one part of it is that I want it to be able to receive text and files from a discord webhook, the text part works fine but when I send the file I can't seem to figure out how to receive it. I looked around for a bit and saw that req.files will return the file but I just get undefined. Here is my api code:

const express = require('express'),
bodyParser = require('body-parser'),
base32 = require('base32'),

const pass = "5'g5?cDzy}\\p5zAwvT[DJ/SeD"
const port = 8080

function denied(res) {
    res.status(403);
    res.send('no');
}

const api = express();
api.use(bodyParser.json());
api.listen(port, () => { console.log(`api running on port ${port}`) });

api.post('/webhook', (req, res) => {
    if (!req.headers) {
        denied(res);
    }
    var auth = req.headers['authorization'];
    if (auth && base32.decode(auth) === pass) {
        console.log(req.files) //undefined
        res.send('done');
    } else {
        denied(res);
    }
});

and this is the code I use to send the file and text:

import requests

key = '6mkped9zcd27mybxbhr3ayj1exv58pu498qn6ta4'

header = {
       "Content-Type": "application/json",
       "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
       'Authorization': key
    }

info = {
        "avatar_url":"https://cdn.discordapp.com/attachments/901070985434918965/904813984753000469/nedladdning_14.jpg",
        "name":"test",
        "embeds": [...]
        }

r = requests.post('http://localhost:8080/webhook', headers=header, json=info)
r2 = requests.post('http://localhost:8080/webhook', headers={'Authorization': key}, files={'file': open('test.zip','rb')})
print(r.text, r.status_code)
print(r2.text, r2.status_code)

CodePudding user response:

Upload files (e.g. how requests does it) are sent as multipart/form-data payloads.

As per body-parser's npm page,

[...] does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules...

You'll need one of those modules, and you'll then need to read its documentation to see if it provides eg. the req.files you've seen somewhere. Otherwise it will indeed be undefined.

  • Related