2017-10-20 61 views
1

我想用Azure函数打开,读取并返回一个HTML文件。我正在开发本地和日志说,该功能成功执行,但在浏览器中,我得到500内部服务器错误。我在这里做错了什么?从Azure功能提供HTML文件时出错

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存在。当我登录htmlContent的内容时,它会给出正确的输出。如果我删除 “内容长度” 在Chrome

Response on Chrome with "Content-Length"

functions.json

​​

响应头的状态代码变为406

Response on Chrome without "Content-Length"

更新1代码似乎在Azure门户上正常运行,但在本地运行时无法正常工作。

+0

只是想你的代码,它工作正常,我(在本地/天蓝色)。你有没有尝试将它部署到天蓝色? –

+0

刚刚在Azure Portal上试用过它,它工作正常。但是由于某些原因,它仍然不在本地工作。 –

+0

什么是“index.html”内容?本地错误是否包含消息(chrome“网络”工具中的响应标签)? –

回答

0

看起来要结合从HTTP返回数据的方法有两种触发功能(context.rescontext.done()):https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#accessing-the-request-and-response

由于您使用context.res,尝试删除context.done();

+0

谢谢,但删除context.done();使该功能无限期地运行。我也尝试使用context.done(null,res)并在输出绑定到“$ return”中设置“name”属性,并得到与我在我的问题中所述相同的结果。 –

0

你做出不正确的使用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.rawcontext.res.send将已经执行context.done你的电话。

请确保您使用content-type=text/html; charset-utf8而不是content-type=text/html,否则您将触发与返回的内容类型有关的问题。而不是返回content-type=text/html你最终得到content-type=text/plain将无法​​呈现您的HTML。

讨论了关于:https://github.com/Azure/azure-webjobs-sdk-script/issues/2053

相关问题