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:
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);
}
}