簡體   English   中英

如何從 url Node Express 獲取參數

[英]How to get params from url Node Express


我正在 Node JS 和 Express 中構建一個優化圖像的應用程序,我需要信息來請求像這樣請求的圖像:
 filename.jpg?w=1280&h=720

該應用程序必須返回一個具有寬度 ( w ) 和高度 ( h ) 的圖像 ( filename.jpg )
這已經有效(我使用 sharp),但我不知道如何從 URL 獲取圖像縮放信息

這是現在的代碼

路由器文件:

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 檔案:

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 檔案:

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

感謝Heiko Theißen

使用req.query

這是解決方案:

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