0

i'am develop backend using node-js and https://www.npmjs.com/package/request to handdle request to main api.

has successfully to send data in the form of string or a number. but I have a problem to send the file. before getting to the request module, i have convert all request from client using

new formdata()

end this is what i code using NPM request

export function requestAPI(method='GET', endpoint='', params={}, callback)
{
    let token = ''
    if(params.token)
    {
        token = params.token;
        delete params.token;
    }

    //set query
    if(params.query)
    {
        endpoint = `${endpoint}?${Url.serialize(params.query)}`
        delete params.query
    }

    //set options
    let options = {
        method: method,
        uri: `${process.env.API_HOST}${endpoint}`,
        timeout: 6000,
        headers: {
            'auth' : token
        },
    };

    // upload files
    // ???

    // using POST method
    if(method === 'POST') {
        options['form'] = params;
    }

    // is upload a file - request via multipart/form-data


    //start request
    try {
        request( options , function(error, response, body){
            if(error)
            {
                console.log(error)
                return callback(httpException(500));
            } else //success
            {
                return callback(JSON.parse(body));
            }
        })
    } catch(err) {
        return callback(httpException(500, err.message+', '+err.stack));
    }
}

2 Answers 2

1

For sending files you will need to use something like multipart/form-data instead of application/json. In addition, you will need to use the formData option instead of form. For example:

var options = {
    method: method,
    uri: `${process.env.API_HOST}${endpoint}`,
    timeout: 6000,
    headers: {
        'auth' : token,
    },
};

// using POST method
if (method === 'POST') {
    options.formData = params;
}

Then inside params you can use any values as outlined in the request and/or form-data modules' documentation. So for local files, you can just use a readable stream:

var fs = require('fs');

// ...

params.avatar = fs.createReadStream('avatar.jpg');

For files you can explicitly set a different filename and/or mime type as shown in the relevant request multipart/form-data example.

Sign up to request clarification or add additional context in comments.

Comments

1

thanks for help guys, finaly i found the answer to solved it.

the problem on this line

if(method === 'POST') {
  options['form'] = params;
}

i just change to this, to make it works

if(method === 'POST') {
  options['formData'] = params;
}

and this is the complete of codes

export function requestAPI(method='GET', endpoint='', params={}, callback)
{
    let token = ''
    if(params.token)
    {
        token = params.token;
        delete params.token;
    }

    //set query
    if(params.query)
    {
        endpoint = `${endpoint}?${Url.serialize(params.query)}`
        delete params.query
    }

    //set options
    var options = {
        method: method,
        uri: `${process.env.API_HOST}${endpoint}`,
        timeout: 30000,
        headers: {
            'auth' : token
        },
    };

    // using POST method
    if(method.toLowerCase() === 'post') {
        options.formData = params;

        // upload files
        if(options.formData.files)
        {
            const files = options.formData.files
            delete options.formData['files']

            Object.keys(files).map(n => {
                options.formData[n] = {
                    value: fs.createReadStream(files[n]._writeStream.path),
                    options: {
                        filename: files[n].name,
                        type: files[n].type
                    }
                }
            })
        }
    }

    //start request
    try {
        request( options , function(error, response, body){
            if(error)
            {
                return callback(httpException(500));
            } else //success
            {
                return callback(JSON.parse(body));
            }
        })
    } catch(err) {
        return callback(httpException(500, err.message+', '+err.stack));
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.