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

时间:2020-04-21 21:23:31

标签: swift httpresponse content-type vapor

我的应用程序使用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标头,因此当在浏览器中打开此路由时,它不会呈现为正确的HTML。在此响应上设置Content-Type标头的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

您需要像这样返回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))
}