Home > Mobile >  How to get params from url Node Express
How to get params from url Node Express

Time:12-16


I'm building an application in Node JS and Express that optimizes images, I need the information to request an image to be requested like this:
filename.jpg?w=1280&h=720

The app will have to The app will have to return an image(filename.jpg) with the width (w) and the height (h)
This already works (I use sharp), but I don't know how to get the image scaling information from the URL

This is the code for now

Router file:

const router = express.Router()

router.get('/:image/:size', Controller.getImage)

Controller file:

export default {
  getImage: [
    async (req, res, next) => {
      try {
        const { image, size } = req.params

        const path = await generateFile(image, size)

        res.sendFile(path)
      } catch (err) {
        next(err)
      }
    }
  ]
}

Function file:

import sharp from 'sharp'

async function generateFile (image, size) {
  const x = options.split('-')[0]
  const y = options.split('-')[1]

  sharp('./img/'   image)
    .resize(x, y)
    .toFile(./resized/   img)
}

CodePudding user response:

Thanks to Heiko Theißen

Use req.query

This is the solution:

getImage: [
  async (req, res, next) => {
    try {
      const { image } = req.params

      const path = await generateFile(image, req.query)

      res.sendFile(path)
    } catch (err) {
      next(err)
    }
  }
]
async function generateFile (image, query) {
  const { x, y } = query

  sharp('./img/'   image)
    .resize(x, y)
    .toFile(./resized/   img)
}
  • Related