Appending param to api request?

Viewed 1325

I have a method that is called, passed a file name, and then makes an API call to the back end to get a preauthorized link. I am attempting to append the parameter (filename) to the end of the URL, but it is causing my API request to 404.

How can I correctly pass a parameter with my API request and get back the preauthorized URL in the response?

My file names may also contain spaces, which I suspect may have something to do with the request returning a 404.

This is the call on my front end:

getPreauthorizedLink(fileName) {   
    console.log(fileName);
    var fileName = fileName;
    var url = 'reportPresignedURL/' + fileName;
    fetch(config.api.urlFor(url))
    .then((response) => response.json())
    .then((url) => {
        console.log(url);
    });
}

And this is the implementation of that API on the back end:

reports.get('/reportPresignedURL/:fileName', async (req, res) => {
    const subscriberID = req.query.subscriberID || 0;

    var AWS = require('aws-sdk');

    var s3 = new AWS.S3();

    var params = { 
        Bucket: config.reportBucket,
        Key: req.params.fileName,
        Expires: 60 * 5
    }

    try {
        s3.getSignedUrl('getObject', params, function (err, url) {
            if(err)throw err;
            console.log(url)
            res.json(url);
        });
    } catch (err) {
        res.status(500).send(err.toString());
    }
});

I have tried isolating the issue down to just how I am passing the param by doing the following on the front end:

  getPreauthorizedLink(fileName){

    console.log(fileName);

    var fileName = fileName;

    var testFileName = 'test';

    var url = 'reportPresignedURL/' + testFileName.replace(/ /g, '%20').replace(/\//g, '%2F');

    fetch(config.api.urlFor(url))
    .then((response) => response.json())
    .then((url) => {

      console.log(url);
  });
  }

This is how I specify the API route in config.js:

reportPresignedURL: '/reports/reportPresignedURL',

I have also tried specifying it like this:

reportPresignedURL: '/reports/reportPresignedURL/:fileName',

For Your Information I have added this API route to my config.js in the front end.

2 Answers

You can use es6 syntax
let url = reportPresignedURL/${fileName}; for Query params

let url = reportPresignedURL/?fileName=${fileName};

Solved it by doing this:

getPreauthorizedLink(fileName){

    console.log(fileName);

    var fileName = fileName;

    let url = config.api.urlFor('reportPresignedURL', fileName);

    fetch(config.api.urlFor(url))
        .then((response) => response.json())
        .then((url) => {

            console.log(url);
        });
}
Related