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

How to set the Content-Type response header in Vapor 4?

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

import Vapor

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

不幸的是,此响应没有正确的 Content-Type HTTP header 设置,因此当此路由在浏览器。对此响应设置 Content-Type header 的最佳方法是什么?

你需要这样returnResponse

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))
}