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)
}
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.
Most helpful comment
In meantime, simple micro server: