嗨,我使用蒸气作为服务器端的快速编程语言。对于文件服务,我在xcode中正确地配置了中间件。但是,服务器本身无法识别文件夹中的index.html
。但是,调用特定文件http://127.0.0.1:8080/index.html
可以正常工作。
如果我只调用http://127.0.0.1:8080/
,那么就会有一个错误
打开(文件:标志:模式:):没有这样的文件或目录(errno: 2)
代码:
import Vapor
import FluentSQL
import FluentKit
import FluentMySQLDriver
// configures your application
public func configure(_ app: Application) throws {
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
app.views.use(.plaintext)
try routes(app)
}
在routes(_ app: Application)
中,我曾经通过下面的方法来提供html文件,但是这也不起作用,并且得到了相同的错误。
app.get("folder") { req in
req.view.render("index.html")
}
如何以编程方式提供html文件,以及如何在调用index.html
时使服务器http://127.0.0.1:8080/
可识别。
发布于 2022-07-25 05:30:10
问题是,您混淆了使用文件中间件和通过路由所提供的服务。您的路由http://127.0.01:8080/folder
正在寻找一个名为index.html
in Resources/Views
的文件--这就是为什么您目前正在收到错误。http://localhost:8080/index.html
之所以工作,是因为在Public
中有一个名为index.html
的文件。
我建议将index.html
移动到Resources/Views
,并通过路由控制访问。对静态内容、JS等使用Public
,而不是实际的网页。
我使用以下方法来定义我的路由。这可以是在configure.swift
中,但是对于较大的应用程序,我倾向于将它放在一个帮助函数中,与其他注册程序放在一个单独的文件中。
try app.register(collection: InsecureController())
控制器的定义是:
struct InsecureController: RouteCollection {
func boot(routes: RoutesBuilder) {
routes.get("", use: index)
routes.get("index.html", use: index)
}
func index(request: Request) async throws -> View {
return try await request.view.render("index.html")
}
}
这将导致应用程序同时响应http://localhost:8080/
和http://localhost:8080/index.html
。
发布于 2022-07-25 10:25:31
蒸气4.54.0在FileMiddleware
中添加了对默认文件的支持。这允许您将index.html
放在Public/folder
中,当向/folder
提出请求时,它将为index.html
提供服务,等等。
在configure.swift中,将FileMiddleware
更改为:
// Serves `index.html` (if it exists) to a request to `http://server.com/`, as well as any subdirectories
app.middleware.use(FileMiddleware(publicDirectory: "public/", defaultFile: "index.html"))
https://stackoverflow.com/questions/73099341
复制相似问题