0

I am taking image url input as query param and further trying to download image from it on my locale then sending it on response(then deleting image on local but not necessary for now). Find complete source code here

Endpoint url I am trying to hit is this

Error I am getting on browser console is, their is no error on server logs: Error screenshot for more clarity in browser console, .

GEThttp://localhost:8082/filteredimage/https://images.all-free-download.com/images/wallpapers_thum/balloon_night_wallpaper_photo_manipulated_nature_wallpaper_1123.jpg?

[HTTP/1.1 404 Not Found 1ms]

Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:8082/favicon.ico (“default-src”).

import express from 'express';
import bodyParser from 'body-parser';
import {filterImageFromURL, deleteLocalFiles} from './util/util';

(async () => {

  // Init the Express application
  const app = express();

  // Set the network port
  const port = process.env.PORT || 8082;
  
  // Use the body parser middleware for post requests
  app.use(bodyParser.json());

  const { expressCspHeader, INLINE, NONE, SELF } = require('express-csp-header');
 
  app.use(expressCspHeader({
      directives: {
          'default-src': [SELF],
          'img-src': ['data:', 'images.com'],
          'worker-src': [NONE],
          'block-all-mixed-content': false
      }
  }));
  // @TODO1 IMPLEMENT A RESTFUL ENDPOINT
  // GET /filteredimage?image_url={{URL}}
  // endpoint to filter an image from a public url.
  // IT SHOULD
  //    1
  //    1. validate the image_url query
  //    2. call filterImageFromURL(image_url) to filter the image
  //    3. send the resulting file in the response
  //    4. deletes any files on the server on finish of the response
  // QUERY PARAMATERS
  //    image_url: URL of a publicly accessible image
  // RETURNS
  //   the filtered image file [!!TIP res.sendFile(filteredpath); might be useful]

  /**************************************************************************** */

  app.get("/filteredimage?image_url={{URL}}",async(req,res)=>{
    console.log("in");
    let { image_url } = req.params.image_url;
    //Validate url
    const isValideUrl = image_url.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
    if(isValideUrl == null)
      return res.status(400).send(`Inavlid url! Try again with valid url`);
    else{
    //Process Image
      const filteredImage = filterImageFromURL(image_url);
      if(filteredImage===undefined||filteredImage===null)
      return res.status(400).send(`Unable to filter image`);
    else
      return res.status(200).sendFile(filteredImage+'');
    }
  })
  //! END @TODO1
  
  // Root Endpoint
  // Displays a simple message to the user
  app.get( "/", async ( req, res ) => {
    res.send("try GET /filteredimage?image_url={{}}")
  } );
  

  // Start the Server
  app.listen( port, () => {
      console.log( `server running http://localhost:${ port }` );
      console.log( `press CTRL+C to stop server` );
  } );
})();

import fs from 'fs';
import Jimp = require('jimp');

// filterImageFromURL
// helper function to download, filter, and save the filtered image locally
// returns the absolute path to the local image
// INPUTS
//    inputURL: string - a publicly accessible url to an image file
// RETURNS
//    an absolute path to a filtered image locally saved file
export async function filterImageFromURL(inputURL: string): Promise<string>{
    return new Promise( async resolve => {
        const photo = await Jimp.read(inputURL);
        const outpath = '/tmp/filtered.'+Math.floor(Math.random() * 2000)+'.jpg';
        await photo
        .resize(256, 256) // resize
        .quality(60) // set JPEG quality
        .greyscale() // set greyscale
        .write(__dirname+outpath, (img)=>{
            resolve(__dirname+outpath);
        });
    });
}

// deleteLocalFiles
// helper function to delete files on the local disk
// useful to cleanup after tasks
// INPUTS
//    files: Array<string> an array of absolute paths to files
export async function deleteLocalFiles(files:Array<string>){
    for( let file of files) {
        fs.unlinkSync(file);
    }
}
Shivam
  • 45
  • 9
  • `Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:8082/favicon.ico (“default-src”).` is irrelevant. Have you tried clicking on the other error? There will be more info about it. – Rojo Jan 08 '21 at 19:03
  • neither of your snippets work. Both say:"Uncaught SyntaxError: Cannot use import statement outside a module" – ControlAltDel Jan 08 '21 at 19:08
  • I@ControlAltDel code snippet won't work on browser because it is project and it requires dependencies to be installed, which is working on my locale. You can pull code and try again, it will work. – Shivam Jan 09 '21 at 07:04
  • @Rojo regarding Content security policy error resolution I have already added code - You can find in my code in server.ts file. I have followed https://stackoverflow.com/questions/56386307/loading-of-a-resource-blocked-by-content-security-policy for resolution but it is not working. – Shivam Jan 09 '21 at 07:08

1 Answers1

2

I would declare the route like that:

app.get("/filteredimage", async(req, res) => {})

Your URL scheme: /filteredimage/?image_url=<URL_HERE>

You can then access the image url in your source code with req.query.image_url.

niklhs
  • 166
  • 9
  • If I am not using "/filteredimage/:image_url"` or "/filteredimage?image_url= then will be able to get input image url. – Shivam Jan 09 '21 at 07:15
  • 1
    Sorry, I was mistaken. With req.params you‘ll need :image_url but if you just use the GET parameters, you don‘t need to declare it in your URL scheme. Please have a look at my updated answer. – niklhs Jan 09 '21 at 11:19
  • Then you could just do a quick check with `if(req.query.image_url)` to verify if the query parameter has been set. In your example you got Cannot GET error from Express because your route definition is not in accordance with your provided url in the browser address bar. – niklhs Jan 09 '21 at 12:35