无论路由如何,如何提供相同的静态文件? [英] How to serve the same static files regardless of the route?

查看:104
本文介绍了无论路由如何,如何提供相同的静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React App.使用webpack,我可以进行生产.现在,我尝试设置一个小型koa服务器来提供由webpack生成的用于生产的静态文件.

I have a react App. With webpack I build for production. Now I try to set a little koa server to serve the static files generated by webpack for production.

所以我做到了

import Koa from 'koa'
import serve from 'koa-static'

const app = new Koa()

app.use(serve('dist/'))

app.listen(3001)

dist/是文件(index.html,bundle等)的目录. 这很好用,但仅适用于路由"/"(本地主机:3001/) 在我的应用程序中,我使用React Router,因此我需要通过示例登录/login(localhost:3001/login).但是当我尝试时,我得到未找到".使用devServer(通过webpack),此路由可以很好地工作.无论路线如何,我都只需要始终服务于/dist即可.怎么做白衣锦鲤?

Where dist/ is the directory where are the files (index.html, bundle etc). This works well but only for the route '/' (localhost:3001/) In my app I use react router so I need to go to /login (localhost:3001/login) by example. But when I try I get "Not Found". With the devServer (by webpack) this route works well. I just need to always serve /dist, whatever the route. How to do this whit koa ?

推荐答案

好,我终于赢了

import Koa from 'koa'
import serve from 'koa-static'
import fs from 'fs'
import path from 'path'

const app = new Koa()
const dist = path.join(__dirname, 'dist')
let validRoutes

fs.readdir(dist, (err, files) => {
  if (err) return console.log('Unable to scan directory: ' + err)
  validRoutes = files
})

function isRouteValid (url) {
  if (!validRoutes || !url) return false
  return validRoutes.find(route => url.slice(1) === route)
}

app.use(async (ctx, next) => {
  if (!isRouteValid(ctx.url)) ctx.path = 'index.html'
  await next()
})

app.use(serve(dist))

app.listen(3010)

这篇关于无论路由如何,如何提供相同的静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆