You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS项目集成Vapor后无法加载JavaScript文件的问题求助

问题:iOS集成Vapor后无法加载JavaScript文件

项目结构

这是我的iOS项目,通过添加'Server'文件夹集成Vapor代码。

FileServer代码

import Vapor
import Leaf

extension URL {
    static func documentsDirectory() throws -> URL {
        try FileManager.default.url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: false)
    }

    func visibleContents() throws -> [URL] {
        try FileManager.default.contentsOfDirectory(at: self,
                                                    includingPropertiesForKeys: nil,
                                                    options: .skipsHiddenFiles)
    }  
}

class FileServer {
    var app: Application
    let port: Int

    init(port: Int) {
        self.port = port
        app = Application(.development)
        configure(app)
    }

    private func configure(_ app: Application) {
        app.http.server.configuration.hostname = "0.0.0.0"
        app.http.server.configuration.port = port
    
        app.views.use(.leaf)
        app.leaf.cache.isEnabled = app.environment.isRelease
        app.leaf.configuration.rootDirectory = Bundle.main.bundlePath
        app.routes.defaultMaxBodySize = "50MB"
    }

    func start() {
        Task(priority: .background) {
            do {
                try app.register(collection: FileWebRouteCollection())
                try app.start()
            } catch {
                fatalError(error.localizedDescription)
            }
        }
    }
}

FileWebRouteCollection代码

import Vapor

struct FileWebRouteCollection: RouteCollection {

    func boot(routes: RoutesBuilder) throws {
        routes.get(use: filesViewHandler)
    }

    func filesViewHandler(_ req: Request) async throws -> View {
        let documentsDirectory = try URL.documentsDirectory()
        let fileUrls = try documentsDirectory.visibleContents()
        let filenames = fileUrls.map { $0.lastPathComponent }
        let context = FileContext(filenames: filenames)
        return try await req.view.render("index", context)
    }
}

struct FileContext: Encodable {
    var filenames: [String]
}

struct FileUploadPostData: Content {
    var file: File
}

index.leaf代码

<!doctype html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Test</title>

<style>
    html {width:100%; height:100%;}
    body {width:100%; height:100%; margin:0;}
</style>

hi

<script type="text/javascript" src="./jsForders/jsFile.js"></script>

</head>
<body>
    <div id="div_canvas" style="width:100%; height:100%;"></div>
</body>
</html>

加载失败截图

运行应用访问Vapor地址时,无法识别上述JavaScript文件,该如何解决?

服务器启动代码

class ViewController: UIViewController {

    var server = FileServer(port: 1206)

    override func viewDidLoad() {
        super.viewDidLoad()
        self.server.start()
    }
}

Vapor服务器通过上述ViewController启动。


解决方案

问题核心是Vapor未配置静态文件服务,无法对外提供JS这类静态资源的访问,按以下步骤修复:

  1. 添加静态文件服务配置
    在FileServer的configure方法中,新增静态资源服务的中间件配置,指定JS文件所在的目录(需确保该目录已打包进App Bundle):
private func configure(_ app: Application) {
    // 原有配置代码保持不变
    
    // 配置静态文件服务,指向JS所在的文件夹
    let jsDirectory = Bundle.main.bundlePath.appending("/jsForders")
    app.middleware.use(FileMiddleware(publicDirectory: jsDirectory))
}
  1. 修正HTML中的JS路径
    由于已将jsForders设为静态根目录,HTML中的引用路径改为:
<script type="text/javascript" src="./jsFile.js"></script>
  1. 验证资源打包状态
    在Xcode中选中jsForders文件夹和jsFile.js,检查右侧面板的"Target Membership"是否勾选了你的App目标,确保资源被正确打包进Bundle。

  2. 可选:规范静态资源目录结构
    更推荐的做法是在项目中创建Public目录,将所有静态资源(JS、CSS、图片等)放入其中,然后配置:

private func configure(_ app: Application) {
    // 原有配置代码保持不变
    
    // 设置Public目录为静态资源根目录
    app.directory.publicDirectory = Bundle.main.bundlePath.appending("/Public")
    app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
}

此时HTML中的JS路径保持./jsForders/jsFile.js即可。


内容的提问来源于stack exchange,提问作者KimJitae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:26:07