无需 Android Studio 即可在本地运行 Flutter Web 应用程序

Red*_*ath 8 dart flutter flutter-web

我有一个使用 Firebase 的云 firestore 的 flutter 应用程序。我已经完成了 Web 构建,并通过 Android Studio 在 Chrome 上运行它,效果很好。我想向我的客户分享我的网络应用程序进度,但不想托管它(因为它尚未完成)。因此,我想找到一种在本地运行它的方法,就像使用 Android Studio 一样,但不需要安装 Android Studio(希望也不需要安装 flutter),这样我就可以将构建文件发送到我的客户,他们可以在他们的机器上运行它(使用脚本在本地启动 Web 服务器并运行 Web 应用程序)。

我已经尝试了 web build 文件夹中包含的以下脚本(index.html 所在的位置)

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from httplib import HTTPResponse
from os import curdir,sep

#Create a index.html aside the code
#Run: python server.py
#After run, try http://localhost:8080/

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path  = '/index.html'
        try:
            sendReply = False
            if self.path.endswith(".html"):
                mimeType = 'text/html'
                sendReply = True
            if sendReply == True:
                f = open(curdir + sep + self.path)
                self.send_response(200)
                self.send_header('Content-type', mimeType)
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
            return
        except IOError:
            self.send_error(404,'File not found!')


def run():
    print('http server is starting...')
    #by default http server port is 80
    server_address = ('127.0.0.1', 8080)
    httpd = HTTPServer(server_address, RequestHandler)
    try:
        print 'http server is running...'
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.socket.close()

if __name__ == '__main__':
    run()
Run Code Online (Sandbox Code Playgroud)

但是当http://localhost:8000在 Chrome 上打开时,我得到一个空白页面,并且控制台显示错误:

Failed to load resource: net::ERR_EMPTY_RESPONSE main.dart.js:1
Failed to load resource: net::ERR_EMPTY_RESPONSE manifest.json:1 
Failed to load resource: net::ERR_EMPTY_RESPONSE :8080/favicon.png:1
Run Code Online (Sandbox Code Playgroud)

我还通过运行尝试了 NPM local-web-serverws --spa index.html但只是得到了ERR_EMPTY_RESPONSE响应。

build/web这是我跑步后的情况flutter build web

构建 web 文件夹文件

如何创建一个本地服务器,可以在本地托管我的 Web 应用程序并在本地运行它,而无需将其托管在 Internet 上?

Yad*_*adu 10

正如您在评论中提到的那样。

创建一个app.js包含以下内容的文件:

const express = require('express')
const app = express()
const port = 8000


app.get('/', (req, res) => {
    console.log('getting request')
    res.sendFile('website/y.html',{root:__dirname})
  })

app.use(express.static(__dirname + '/website'))

app.use((req, res)=>{
    res.redirect('/')
})

app.listen(port, () => {
    console.log(`app listening at http://localhost:${port}`)
  })
Run Code Online (Sandbox Code Playgroud)

这里我的网站文件存在于website文件夹中,我的入口点是y.html. 设置静态文件目录(您的网站页面),然后为根请求提供 .html

最后,要运行它,请打开终端并移动到根文件夹。然后做

npm init
npm install express --no-save
node app.js
Run Code Online (Sandbox Code Playgroud)