我仍在学习节点,但有一件事我无法在任何地方找到答案。
我正在尝试部署一个简单的代码来读取URL的内容。它在localhost上运行良好,但是当我部署到我的azure应用程序时,它根本不起作用。
当我访问浏览器上的链接时,它显示空白屏幕。
这是代码
var http = require('http');
var server = http.createServer(function(request, response) {
const url = "http://www.google.com";
response.writeHead(200, {"Content-Type": "text/plain"});
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log("End of response", port);
response.end('End of response.<br/>');
});
});
});
var port = process.env.PORT || 1337;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
最佳答案
当我访问浏览器上的链接时,它显示空白屏幕。
我之前遇到过类似的问题,我尝试访问http://cn.bing.com
,但是请求将自动重定向到https
,并且没有任何响应内容。
根据您的代码,我创建了azure Web应用程序来检查此问题。
app.js:
var http = require('http');
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
http.get("http://www.google.com", res => {
//check the status code
console.log(res.statusCode+','+res.headers['location']);
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log("End of response", port);
response.end(body);
});
}).on('error',(e)=>{ //catch the error
console.error('Got error:'+e);
response.end('Got exception:'+e);
});
});
var port = process.env.PORT || 1337;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
我的项目内容通过KUDU看起来像这样。
测试:
要验证日志,您可以Enable diagnostics logging并检查您的应用程序日志。另外,您可以将
iisnode.yml
文件添加到Web应用程序的根文件夹中,并指定您的日志配置,详细信息可以遵循Debug Node.js Web Apps on Azure。另外,这里有一些相关的教程,您可以参考它们:
http.get(options[, callback])
How to deploy a node.js site into Azure Web App to create a Website
Create a Node.js web app in Azure