Serve: middleware support

Created on 19 Sep 2017  路  3Comments  路  Source: vercel/serve

This issue continues https://github.com/zeit/micro/issues/225 conversation about how to use micro + serve.

In my case, I want to server an static file (index.html with js and css) under no query params, like a main entry page to the API.

Expected API inspired in serve-static:

const {middleware} = require('server')
const servePublic = middleware(path.join(__dirname, 'public'))

module.exports = (req, res) => {
  res.send(servePublic)
}

Most helpful comment

In meantime, simple micro server:

const url = require('url')
const fs = require('fs')
const path = require('path')
const { send } = require('micro')
const mime = require('mime')

module.exports = async (req, res) => {
  const parseUrl = url.parse(req.url)
  let file = `.${parseUrl.pathname}`

  fs.exists(file, exist => {
    if (!exist) {
      send(res, 404)
      return
    }

    if (fs.statSync(file).isDirectory()) {
      file += '/index.html'
    }

    fs.readFile(file, (err, data) => {
      if (err) {
        send(res, 500)
      } else {
        res.setHeader('Content-type', mime.getType(file))
        send(res, 200, data)
      }
    })
  })
}

All 3 comments

In meantime, simple micro server:

const url = require('url')
const fs = require('fs')
const path = require('path')
const { send } = require('micro')
const mime = require('mime')

module.exports = async (req, res) => {
  const parseUrl = url.parse(req.url)
  let file = `.${parseUrl.pathname}`

  fs.exists(file, exist => {
    if (!exist) {
      send(res, 404)
      return
    }

    if (fs.statSync(file).isDirectory()) {
      file += '/index.html'
    }

    fs.readFile(file, (err, data) => {
      if (err) {
        send(res, 500)
      } else {
        res.setHeader('Content-type', mime.getType(file))
        send(res, 200, data)
      }
    })
  })
}

it serves only static html file.

i want to whole bundle of html,css,and js. for example we serve public directory in express nodejs framework.

const docs = cors(async(req, res) => {
   let file = path.join(__dirname, './public');

  fs.exists(file, exist => {
    if (!exist) {
      send(res, 404)
      return
    }

    if (fs.statSync(file).isDirectory()) {
      file += path.join(__dirname, './public');
    }

    fs.readFile(file, (err, data) => {
      if (err) {
        send(res, 500)
      } else {
        res.setHeader('Content-type', mime.getType(file))
        send(res, 200, data)
      }
    })
  })
})

Thank you for the effort you've put into this!

This is now possible. All thanks to serve-handler, as described in the notes for the new release.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Simran-B picture Simran-B  路  4Comments

leo picture leo  路  5Comments

leo picture leo  路  5Comments

Olexiy665 picture Olexiy665  路  3Comments

malinda1986 picture malinda1986  路  6Comments