如何在Vapor 4中设置Content-Type响应头?

Max*_*tov 4 content-type httpresponse swift vapor

我的应用程序使用 Vapor 4.3 并具有发送 HTML 片段作为响应的简单路由:

import Vapor

func routes(_ app: Application) throws {
  app.get("hello") { _ -> String in
    "<html><body>Hello, world!</body></html>"
  }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,此响应没有Content-Type设置正确的 HTTP 标头,因此当在浏览器中打开此路由时,它不会呈现为正确的 HTML。在此响应上设置标头的最佳方法是什么Content-Type

imi*_*ike 9

你需要Response这样返回

app.get("hello") { _ -> Response in
    var headers = HTTPHeaders()
    headers.add(name: .contentType, value: "text/html")
    let html = "<html><body>Hello, world!</body></html>"
    return Response(status: .ok, headers: headers, body: .init(string: html))
}
Run Code Online (Sandbox Code Playgroud)