简体   繁体   English

如何从 url Node Express 获取参数

[英]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: 我正在 Node JS 和 Express 中构建一个优化图像的应用程序,我需要信息来请求像这样请求的图像:
 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 )该应用程序必须返回一个具有宽度 ( w ) 和高度 ( h ) 的图像 ( filename.jpg )
This already works (I use sharp), but I don't know how to get the image scaling information from the URL这已经有效(我使用 sharp),但我不知道如何从 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: Controller 档案:

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: Function 档案:

 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感谢Heiko Theißen

Use req.query使用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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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