【问题标题】:Prototyping: Simplest HTTP server with URL routing (to use w/ Backbone.Router)?原型设计:最简单的带有 URL 路由的 HTTP 服务器(与 Backbone.Router 一起使用)?
【发布时间】:2012-05-27 18:31:25
【问题描述】:

我们正在开发一个 Backbone.js 应用程序,我们可以通过键入 python -m SimpleHTTPServer 来启动 HTTP 服务器这一事实非常棒。

我们希望能够将任何 URL(例如 localhost:8000/path/to/something)路由到我们的 index.html,以便我们可以使用 HTML5 pushState 测试 Backbone.Router。

实现这一目标最轻松的方法是什么? (为了快速制作原型)

【问题讨论】:

  • localhost/path_to_nowhere 将引导您到nowhere。但是localhost/path/somewhere_in_nowhere 可以按照您的预期将您带到任何地方。要将任何 url 路由到端点(目标 url),您必须首先加载包含主干、下划线、jquery 的页面,对吗?您还应该引导一个路由到端点 url 的路由器。
  • 我想你误解了我的问题。当您在启用 pushState 的 Backbone 应用程序中时,您的 URL 将在您浏览您的应用程序时更改为 http://localhost:8000/some/path/in/my/app。但是对于 SimpleHTTPServer,如果此时刷新页面,您将收到 404,因为服务器会尝试获取该 URL 的资源。我正在寻找一种方法来允许服务器将任何 URL 重新路由回index.html。

标签: backbone.js prototyping httpserver simplehttpserver backbone-routing


【解决方案1】:

只需使用BaseHTTPServer中的内置python功能

import BaseHTTPServer

class Handler( BaseHTTPServer.BaseHTTPRequestHandler ):
    def do_GET( self ):
        self.send_response(200)
        self.send_header( 'Content-type', 'text/html' )
        self.end_headers()
        self.wfile.write( open('index.html').read() )

httpd = BaseHTTPServer.HTTPServer( ('127.0.0.1', 8000), Handler )
httpd.serve_forever()

【讨论】:

  • 如果您确实想按原样加载某些文件怎么办?
  • @snapfractalpop 我不确定你在问什么。这将按原样发送index.html。
  • 我想知道您想按原样加载的静态资产(而不是为它们提供 index.html)。对于我措辞不当的评论,我深表歉意。
  • @snapfractalpop 啊,我明白了。您必须编写一些代码来解析self.path 并相应地路由请求。尽管除了真正简单的路由之外,我可能会建议使用烧瓶(或替代方法),而不是使用 BaseHTTPServer 自己重新实现 HTTP 路由。
【解决方案2】:
  1. 下载安装CherryPy

  2. 创建以下 python 脚本(将其称为 always_index.py 或类似名称)并将 'c:\index.html' 替换为您要使用的实际文件的路径

    import cherrypy
    
    class Root:
        def __init__(self, content):
            self.content = content
    
        def default(self, *args):
            return self.content
        default.exposed = True
    
    cherrypy.quickstart(Root(open('c:\index.html', 'r').read()))
    
  3. 运行python <path\to\always_index.py>
  4. 将您的浏览器指向http://localhost:8080,无论您请求什么网址,您始终会获得相同的内容。

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 1970-01-01
    • 2013-02-18
    • 2017-06-14
    • 1970-01-01
    • 2015-03-31
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多