简体   繁体   中英

How to get params from url Node Express


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:

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)
      }
    }
  ]
}

Controller 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)
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM