首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >服务器不认为Swift Vapor index.html是默认的

服务器不认为Swift Vapor index.html是默认的
EN

Stack Overflow用户
提问于 2022-07-24 14:36:20
回答 2查看 129关注 0票数 1

嗨,我使用蒸气作为服务器端的快速编程语言。对于文件服务,我在xcode中正确地配置了中间件。但是,服务器本身无法识别文件夹中的index.html。但是,调用特定文件http://127.0.0.1:8080/index.html可以正常工作。

如果我只调用http://127.0.0.1:8080/,那么就会有一个错误

打开(文件:标志:模式:):没有这样的文件或目录(errno: 2)

代码:

代码语言:javascript
运行
复制
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文件,但是这也不起作用,并且得到了相同的错误。

代码语言:javascript
运行
复制
app.get("folder") { req in
     
    req.view.render("index.html")
}

如何以编程方式提供html文件,以及如何在调用index.html时使服务器http://127.0.0.1:8080/可识别。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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中,但是对于较大的应用程序,我倾向于将它放在一个帮助函数中,与其他注册程序放在一个单独的文件中。

代码语言:javascript
运行
复制
try app.register(collection: InsecureController())

控制器的定义是:

代码语言:javascript
运行
复制
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

票数 1
EN

Stack Overflow用户

发布于 2022-07-25 10:25:31

蒸气4.54.0FileMiddleware中添加了对默认文件的支持。这允许您将index.html放在Public/folder中,当向/folder提出请求时,它将为index.html提供服务,等等。

在configure.swift中,将FileMiddleware更改为:

代码语言:javascript
运行
复制
// 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"))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73099341

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档