从Azurefunction提供HTML文件时出错
我正尝试使用Azure函数打开,读取并返回一个HTML文件。 我在本地开发和日志说,function成功执行,但在浏览器中,我得到500内部服务器错误。 我在这里做错了什么?
const fs = require('fs'); const path = require('path'); const mime = require('../node_modules/mime-types'); module.exports = function (context, req) { const staticFilesFolder = 'www/build/'; const defaultPage = 'index.html'; getFile(context, req.query.file); function getFile(context, file) { const homeLocation = process.env["HOME"]; if(!file || file == null || file === undefined){ context.done(null,{status:200,body:"<h1>Define a file</h1>",headers:{ "Content-Type":" text/html; charset=utf-8" }}); } fs.readFile(path.resolve(path.join(homeLocation, staticFilesFolder, file)), (err, htmlContent) => { if (err) { getFile(context, "404.html"); } else { const res = { status: 200, body: htmlContent, headers:{ "Content-Type": mime.lookup(path.join(homeLocation, staticFilesFolder, file)) } } context.done(null,res); } }) } };
注意我确定存在404.html和index.html。 当我logginghtmlContent
的内容时,它提供了正确的输出。
functions.json
{ "disabled": false, "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "methods":["get"], "route":"home", "name": "req" }, { "type": "http", "direction": "out", "name": "res" } ] }
Chrome上的回应
如果我删除了“Content-Length”标题,状态码将变为406。
更新1代码似乎在Azure门户上正常运行,但在本地运行时无法正常工作。
看起来你正在结合两种从http触发函数( context.res
和context.done()
)返回数据的方法: https : //docs.microsoft.com/en-us/azure/azure-functions/functions-参考节点#访问最请求-响应
由于您使用的是context.res
,请尝试删除context.done();
您正在使用context.res
,您不应该覆盖它,而是利用Azure NodeJS worker中提供的Response类提供的方法。 如果您正在使用VSCode,您将获得这些方法的智能感知。 否则请参阅: https : //github.com/Azure/azure-functions-nodejs-worker/blob/dev/src/http/Response.ts
你的代码应该看起来像这样。
context.res.setHeader('content-type', 'text/html; charset=utf-8') context.res.raw(htmlContent)
使用context.res.raw
或context.res.send
将已经为您执行context.done
调用。
确保你使用的是 content-type=text/html; charset-utf8
content-type=text/html; charset-utf8
而不是content-type=text/html
否则你将触发一个返回的内容types的问题。而不是返回的 content-type=text/html
你最终得到的content-type=text/plain
将无法呈现您的HTML。
解答: https : //github.com/Azure/azure-webjobs-sdk-script/issues/2053