Search code examples
node.jsform-data

Form Data with node js statusCode:307, statusMessage:'Temporary Redirect'


What is wrong with the following set up?

    var form = new FormData();
    form.append('something', fs.createReadStream(filePath));
    form.append('data', JSON.stringify({
        "stuff": "hi"
    }));

    form.submit({
        host: "example.com",
        path: `/blah`,
        headers: {
            "Authorization": `...`
        }
    }, function (err, res) {
        res.resume();
    });

The issue is that i'm seeing: statusCode:307, statusMessage:'Temporary Redirect' if I inspect res

Is there anything wrong with how i'm submitting the form?

What does res.resume() do?

I have been trying to follow this: https://www.npmjs.com/package/form-data


Solution

  • This may have been a very specific problem to me and I've unfortuantely lost track of the specific detail that made this work. However, for the good of humanity, here is the code that does work now (i've obfuscated a bunch if you're wondering why things are ... etc)

    async uploadMedia(...) {
        const url = `...`;
    
        var form = new FormData();
        form.append('x', fs.createReadStream(filePath));
        form.append('y', JSON.stringify({
            ...
        }));
    
        let headers = this.#getHeaders();
        delete headers['Content-Type'];
    
        return new Promise((resolve, reject) => {
            const req = form.submit({
                method: 'PUT',
                host: process.env.GATEWAY_API_URL,
                path: `/api/...`,
                protocol: 'https:',
                headers: headers
            }, function (err, res) {
                if (err) {
                    return reject(new Error(err.message));
                }
    
                if (res.statusCode < 200 || res.statusCode > 299) {
                    return reject(new Error(`HTTP status code ${res.statusCode}`));
                }
    
                const body = []
                res.on('data', (chunk) => body.push(chunk))
                res.on('end', () => {
                    const resString = Buffer.concat(body).toString();
                    resolve(resString);
                })
            });
        })
    }