egg.js中通过fs加载html界面,但由于ctx.set('Content-Type','text/html')的mime类型限制,配套的css和js都无法正常加载
发布于 6 年前 作者 hanqizheng 4842 次浏览 来自 问答

求大佬解答

18 回复

带可复现代码库提 issue

大佬我只是想问一下,有什么办法可以让配套的css和js不会因为Content-type的限制一起加载出来。。。是我自己程序的问题,不是egg的错(大哭.jpg)

我的意思是看不懂你的描述。。。都是程序员,就不能直接 show me the code 来对话么

//     /app/controller/docs.js 
//...
  async renderDoc(){
    const docName = this.ctx.params.docName;
	
    const docInfo = await this.service.docs.find(docName);

    if(docInfo === false){
      this.ctx.status = 404;
      this.ctx.body = 'Not Found';
    }
    else{  
      const filePath = '' + docInfo.doc.path;
    
      this.ctx.set('Content-Type','text/html');  

      this.ctx.body = fs.readFileSync(filePath);
    }
  }

报的错误是

eco:1 Refused to apply style from 'http://127.0.0.1:7001/docs/_static/css/theme.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

类似这种错误的好几条,都是not supported

emmmmmm,我的描述…我尽力了

docs/_static/css/theme.css 这个路由是谁处理的?

明显是路由写错了~ renderDoc 匹配到了静态资源

八成是路由的问题,theme.css应该是静态资源吧?你自己访问 http://127.0.0.1:7001/docs/static/css/theme.css 看看是不是走 renderDoc 了?可以贴一下看看router.js里怎么配置的。

来自✨ Node.js开源项目精选✨*

this.ctx.set('Content-Type','text/html');  

前面加个请求后缀的switch

谢谢大家,照着大家的我改出来,谢谢各位大佬!!

  • readFileSync 别用,会死
  • 静态资源为啥不放 CDN 或者放到 public 下,要自己搞

pipe pipe pipe 这么读服务器压力小一点

@burning0xb 每次都读也不行的,这种肯定要 cache 的

@atian25 @hanqizheng 采用大佬的建议 读缓存比较好

静态资源直接走nginx了吧

静态资源应该上 CDN

@atian25 好的,我有看到别的帖子,也是大佬你强调的不要用Sync,我改了。 还有就是放在public下面他可以成功,但是觉得并没有走我写好的路由就成功了?因为对应controller的console.log()没有执行,所以觉得没有走我写的路由。

@hanqizheng 静态资源为什么要走 Controller 了。。。就入口文件用 Controller render 即可

回到顶部