Google Firebase Hosting 背后的 Cloud Function,JSON 响应被转换为 HTML,如何禁用这种行为?
Google Cloud Function behind Firebase Hosting, JSON response is converted into HTML, how to disable such behavior?
我们在我们的项目中使用 Firebase,我们有一堆云功能,我们已经启用了通过 Firebase 托管访问这些功能。
在我们的 'firebase.json':
"rewrites": [
{
"source": "/api/**",
"function": "api"
}
],
这在我们查询端点时工作正常,但是,托管服务器似乎混淆了我们 back-end 的响应,而不是返回原始 json(我们需要 deploy/show 错误),它 returns 一个 html 编码的响应。
以及响应中的 header:
你可以看到 Content-Type
header 正在返回 html...所有这些都是非常令人困惑的行为,因为所有的 Firebase 魔法...有什么办法关闭此行为?我浏览了文档但找不到任何内容,我需要 cloud-functions 的回复 as-is。
发现问题,我们根本没有在我们的 Firebase 函数中设置任何 Content-Type
header,如果您设置它们,Firebase 托管会尊重它们。
在 Express 中你可以设置全局 header:
app.use(function (_, res, next) {
res.header('Content-Type', 'application/json')
next()
})
请注意不要破坏其他端点。
根据 MDN,“Content-Type header 告诉客户端返回内容的内容类型实际上是什么”
您可以为每个端点分别指定 content-type 或使用 Express Middlewares。中间件函数在路由中的每个端点之前执行。例如,在你的路线 /api
中,你可以这样做:
app.use("/api", function (_, res, next) {
//The follow code will be executed only for the /api route
res.header('Content-Type', 'application/json')
next() //goes to the next middleware or the route
})
我们在我们的项目中使用 Firebase,我们有一堆云功能,我们已经启用了通过 Firebase 托管访问这些功能。
在我们的 'firebase.json':
"rewrites": [
{
"source": "/api/**",
"function": "api"
}
],
这在我们查询端点时工作正常,但是,托管服务器似乎混淆了我们 back-end 的响应,而不是返回原始 json(我们需要 deploy/show 错误),它 returns 一个 html 编码的响应。
以及响应中的 header:
你可以看到 Content-Type
header 正在返回 html...所有这些都是非常令人困惑的行为,因为所有的 Firebase 魔法...有什么办法关闭此行为?我浏览了文档但找不到任何内容,我需要 cloud-functions 的回复 as-is。
发现问题,我们根本没有在我们的 Firebase 函数中设置任何 Content-Type
header,如果您设置它们,Firebase 托管会尊重它们。
在 Express 中你可以设置全局 header:
app.use(function (_, res, next) {
res.header('Content-Type', 'application/json')
next()
})
请注意不要破坏其他端点。
根据 MDN,“Content-Type header 告诉客户端返回内容的内容类型实际上是什么”
您可以为每个端点分别指定 content-type 或使用 Express Middlewares。中间件函数在路由中的每个端点之前执行。例如,在你的路线 /api
中,你可以这样做:
app.use("/api", function (_, res, next) {
//The follow code will be executed only for the /api route
res.header('Content-Type', 'application/json')
next() //goes to the next middleware or the route
})