Node-LokiJS:并非所有获取请求都得到满足,请求状态永远待定吗? 通过ID检索图像的API Index.ts(所有API) Index.html utils.ts

我按照本教程进行了关于使用multer-express上传文件的操作,然后按ID Scoth.io检索图像。

安装程序使用LokiJS作为数据库。

所有API都可以正常工作,但是当按ID检索多个图像的API不适用于多个图像时。大多数获取请求都在服务器上挂起(状态在Chrome Dev工具的“网络”面板中处于挂起状态)。

请求永远不会在待处理状态(永远待处理)中完成,而服务器会陷入其中。

Node-LokiJS:并非所有获取请求都得到满足,请求状态永远待定吗?
      
    通过ID检索图像的API  Index.ts(所有API) Index.html  utils.ts

通过ID检索图像的API

app.get('/images/:id',async (req,res) => {
    try {
        const col = await loadCollection(COLLECTION_NAME,db);
        const result = col.get(req.params.id);

        if (!result) {
            res.sendStatus(404);
            return;
        };

        res.setHeader('Content-Type',result.mimetype);
        fs.createReadStream(path.join(UPLOAD_PATH,result.filename)).pipe(res);
    } catch (err) {
        res.sendStatus(400);
    }
})

Index.ts(所有API)

import * as express from 'express'
import * as multer from 'multer'
import * as cors from 'cors'
import * as fs from 'fs'
import * as path from 'path'
import * as Loki from 'lokijs'

import { loadCollection,imageFilter } from './utils'

//setup
  const DB_NAME = 'db.json'
  const COLLECTION_NAME = 'images'
  const UPLOAD_PATH = 'uploads'
  const upload = multer({ dest: `${UPLOAD_PATH}/`,fileFilter: imageFilter }) //MULTER CONFIG
  const db = new Loki(`${UPLOAD_PATH}/${DB_NAME}`,{ persistenceMethod: 'fs' })

// app  
  const app = express();
  app.use(cors());

  app.get('/',(req,res) => {
    res.json({responseText : 'Server running successfully'})
  })


  //Upload Single
  app.post('/fileUpload',upload.single('file'),res) => {

    try {
        const col = await loadCollection(COLLECTION_NAME,db)
        const data = col.insert(req.file)

        db.saveDatabase()
        res.send({id: data.$loki,fileName: data.filename,originalName: data.originalname })
      } catch (err) {
        res.sendStatus(400)
      }
  })

//Upload Multiple
 app.post('/photos/upload',upload.array('photos',12),db)
        const data = [].concat(col.insert(req.files))

        db.saveDatabase()
        res.send(data.map(x => ({ id: x.$loki,fileName: x.filename,originalName: x.originalname })));
    } catch (err) {
        res.sendStatus(400)
      }
  })

 //Retrieve Image
 app.get('/images',res) => {
   try {
       const col = await loadCollection(COLLECTION_NAME,db)
       res.send(col.data)
   } catch(err) {
     res.sendStatus(400)
   }
 })


// Retrieve Image by Id
 app.get('/images/:id',res) => {
   try {

       const col = await loadCollection(COLLECTION_NAME,db)
       const result = col.get(parseInt(req.params.id))

       if(!result) {
         res.sendStatus(404)
         return;
       }

     res.setHeader('Content-Type',result.mimetype);
     fs.createReadStream(path.join(UPLOAD_PATH,result.filename)).pipe(res)
   } catch(err) {
     res.sendStatus(400)
   }
 })

app.listen(3000,function () {
    console.log('listening on port 3000!');
})

Index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Fetch Image (NodeJS-LokiJS API) - Example</title>
    <style>
      .photo {
        width: 100px;
        display: block;
        margin-bottom: 5px;
        border: 2px solid black;
      }
    </style>    
  </head>
  <body>
    <h1>HTML Example</h1>
    <p>
      JPEG:<br>
      <img class="photo" src="http://localhost:3000/images/1">
      <img class="photo" src="http://localhost:3000/images/2">
      <img class="photo" src="http://localhost:3000/images/3">
      <img class="photo" src="http://localhost:3000/images/4">
      <img class="photo" src="http://localhost:3000/images/5">
      <img class="photo" src="http://localhost:3000/images/6">
    </p>
  </body>
</html>

utils.ts

import * as del from 'del'
import * as Loki from 'lokijs'

const loadCollection = function (colName,db: Loki): Promise<Loki.Collection<any>> {
    return new Promise(resolve => {
    db.loadDatabase({},_=> {
      const _collection = db.getcollection(colName) || db.addCollection(colName)
      resolve(_collection)
    })
  })
}

const imageFilter = function (req,file,cb) {
    // accept image only
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
        return cb(new Error('Only image files are allowed!'),false);
    }
    cb(null,true);
}

export { imageFilter,loadCollection }

as3861701 回答:Node-LokiJS:并非所有获取请求都得到满足,请求状态永远待定吗? 通过ID检索图像的API Index.ts(所有API) Index.html utils.ts

看起来loadCollection确实存在问题。 从db.loadDatabase中删除loadCollection,并在初始化后仅将它一次加载到index.ts中。

index.ts

import * as express from 'express'
import * as multer from 'multer'
import * as cors from 'cors'
import * as fs from 'fs'
import * as path from 'path'
import * as Loki from 'lokijs'

import { loadCollection,imageFilter } from './utils'

//setup
  const DB_NAME = 'db.json'
  const COLLECTION_NAME = 'images'
  const UPLOAD_PATH = 'uploads'
  const upload = multer({ dest: `${UPLOAD_PATH}/`,fileFilter: imageFilter }) //MULTER CONFIG
  const db = new Loki(`${UPLOAD_PATH}/${DB_NAME}`,{ persistenceMethod: 'fs' })
  db.loadDatabase({});

// app  
  const app = express();
  app.use(cors());

  app.get('/',(req,res) => {
    res.json({responseText : 'Server running successfully'})
  })


  //Upload Single
  app.post('/fileUpload',upload.single('file'),async (req,res) => {

    try {
        const col = await loadCollection(COLLECTION_NAME,db)
        const data = col.insert(req.file)

        db.saveDatabase()
        res.send({id: data.$loki,fileName: data.filename,originalName: data.originalname })
      } catch (err) {
        res.sendStatus(400)
      }
  })

//Upload Multiple
 app.post('/photos/upload',upload.array('photos',12),db)
        const data = [].concat(col.insert(req.files))

        db.saveDatabase()
        res.send(data.map(x => ({ id: x.$loki,fileName: x.filename,originalName: x.originalname })));
    } catch (err) {
        res.sendStatus(400)
      }
  })

 //Retrieve Image
 app.get('/images',res) => {
   try {
       const col = await loadCollection(COLLECTION_NAME,db)
       res.send(col.data)
   } catch(err) {
     res.sendStatus(400)
   }
 })


// Retrieve Image by Id
 app.get('/images/:id',res) => {
   try {

       const col = await loadCollection(COLLECTION_NAME,db)
       const result = col.get(parseInt(req.params.id))

       if(!result) {
         res.sendStatus(404)
         return;
       }

     res.setHeader('Content-Type',result.mimetype);
     fs.createReadStream(path.join(UPLOAD_PATH,result.filename)).pipe(res)
   } catch(err) {
     res.sendStatus(400)
   }
 })

app.listen(3000,function () {
    console.log('listening on port 3000!');
})

utils.ts

import * as del from 'del'
import * as Loki from 'lokijs'

const loadCollection = function (colName,db: Loki): Promise<Loki.Collection<any>> {
    return new Promise(resolve => {
      const _collection = db.getCollection(colName) || db.addCollection(colName)
      resolve(_collection)
  })
}

const imageFilter = function (req,file,cb) {
    // accept image only
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
        return cb(new Error('Only image files are allowed!'),false);
    }
    cb(null,true);
}

export { imageFilter,loadCollection }
本文链接:https://www.f2er.com/3137586.html

大家都在问