在 Azure 中配置节点应用程序

Configure node app in azure

我已经在 Azure 中部署了一个节点应用程序并想要对其进行配置。这是我要测试的文件"index.js"的内容:

const express = require('express');
const app = express();
const bodyparser = require('body-parser');
const cors = require('cors');

var cats = [{name:'Lily'}, {name: 'Lucy'}];

var corOptions = {
    origin: '*',
    optionsSuccessStatus: 200
};
app.use(cors(corOptions));
app.listen(3000,() =>{
    console.log('Server started :)');
});
app.route('/api/cats').get((req, res) =>{
    console.log(req.hostname);
    console.log(req);
    res.send(cats);
});
console.log("Server is running...");

这是 package.json 文件

{
"name": "app-service-hello-world",
"description": "Simple Hello World Node.js sample for Azure App Service",
"version": "0.0.1",
"private": true,
"license": "MIT",
"author": "Microsoft",
"engines": {
    "node": ">=6.9.1"
},
"scripts": {
    "start": "node index.js"
},
"dependencies": {
    "cors": "^2.8.4",
    "express": "^4.16.3"
}
}

web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <webSocket enabled="false" />
    <handlers>
      <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
      <add name="iisnode" path="index.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^index.js\/debug[\/]?" />
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="index.js"/>
        </rule>
      </rules>
    </rewrite>
    
    <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Make sure error responses are left untouched -->
    <httpErrors existingResponse="PassThrough" />

    <!--<iisnode watchedFiles="web.config;*.js"/>-->
  </system.webServer>
</configuration>

我正在使用以下 URL 测试应用程序,但没有得到预期的输出:https://firstnodeapp1.azurewebsites.net/api/cats

我在本地测试为 http://localhost:8000/api/cats,它工作正常。所以,其实很在意少了什么。

如果能帮助我正确配置它,我将不胜感激。

将端口更改为 process.env.port 并重新部署您的代码应该可以工作。

说明:

Azure Web App 是 sand box 的一个模型,通过仅有的两个已经公开的 80(HTTP) 和 443(HTTPS) TCP 端口访问。

使用process.env.port,Azure会为你的Nodejs服务器创建一个命名管道来监听,并将来自443端口的请求传递到命名管道。您的应用内的任何特定端口无效,将导致服务器内部错误 (500)。