无法运行Node JS部署到Azure

时间:2018-05-21 20:02:05

标签: javascript node.js azure

我遵循了本教程:

https://docs.microsoft.com/en-us/azure/app-service/app-service-web-get-started-nodejs

我使用" Zip Deploy"部署了一个Express JS应用程序。工具:

https://[app_name_here].scm.azurewebsites.net/ZipDeploy

当我尝试调用我的公共API时,我不断收到错误消息" 您要查找的资源已被删除,名称已更改或暂时无法使用。& #34;

奇怪的是,我的Express JS应用程序在本地运行得很好。我尝试多次更改index.js以正确显示我的API路径,但似乎没有任何工作在Azure上。这是我目前的代码。

我承认它有点混乱/凌乱,因为我已经合并了3种不同的Express应用程序的逻辑。

...

index.js

var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();
var cookieParser = require('cookie-parser');
var path = require('path');
app.use(cors({ origin:'*' }));
app.set('port', (process.env.PORT || 5000));
app.use(bodyParser.json());

var indexRouter = require('./routes/index');
app.set('views', path.join(__dirname, 'views'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

//Router imports
var chainCoreDevRoutes = require('./routes/chainCoreDevRoutes');
var mongoDevRoutes = require('./routes/mongoDevRoutes');
var stuffMartServiceRoutes = require('./routes/stuffMartServiceRoutes');
app.use('/dev/chainCore', chainCoreDevRoutes);
app.use('/dev/mongo', mongoDevRoutes);
app.use('/api', stuffMartServiceRoutes);

//app.get('*', function(request, response) { response.sendFile(path.join(__dirname, 'public/index.html')); });

app.listen(app.get('port'), function() {
  console.log('Node app is running wubbalubba dub dub! on port', app.get('port'));
});

...

路由/ index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

...

web.config(Azure环境需要)

<configuration>
    <system.webServer>

        <!-- indicates that the index.js file is a node.js application 
        to be handled by the iisnode module -->

        <handlers>
            <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
        </handlers>

        <!-- adds index.js to the default document list to allow 
        URLs that only specify the application root location, 
        e.g. http://mysite.antarescloud.com/ -->

        <defaultDocument enabled="true">
            <files>
                <add value="index.js" />
            </files>
        </defaultDocument>

      </system.webServer>
</configuration> 

3 个答案:

答案 0 :(得分:0)

我使用express generate来创建我的简单项目,然后将其成功部署到azure。请参阅我的文件。

<强> app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.set('port', process.env.PORT || 5000);

console.log("+++++++++++++++"+ app.get('port'));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

app.listen(app.get('port'), function(){
          console.log('Express server listening on port ' + app.get('port'));
          });

<强> 的web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
     This configuration file is required if iisnode is used to run node processes behind
     IIS or IIS Express.  For more information, visit:

     https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->

<configuration>
  <system.webServer>
    <!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
    <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="app.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="^app.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="app.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" />

    <!--
      You can control how Node is hosted within IIS using the following options:
        * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
        * node_env: will be propagated to node as NODE_ENV environment variable
        * debuggingEnabled - controls whether the built-in debugger is enabled

      See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
    -->
    <iisnode watchedFiles="web.config;*.js"/>
  </system.webServer>
</configuration>

<强> 路由/ index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

访问结果:

enter image description here

您可以查看差异。有任何疑虑,请告诉我。

答案 1 :(得分:0)

我的解决方案: 请勿按照教程/博客

进行操作

我使用Visual Studio 2017,找到了一个名为“Basic Azure Node.js Express 4 App”的项目模板。基础项目运作良好,只需5分钟即可完成设置。

答案 2 :(得分:0)

部署nodejs的最简单方法是使用终端。

您只需像在普通计算机上一样将项目克隆到服务器即可。 做“ npm安装” 通过“ npm start”或“ node index.js”运行项目(取决于您的文件名)。 检查程序是否在服务器中启动,最好使用邮递员测试api是否正常工作。 如果有错误,请修复它们。 如果不是,请在服务器计算机上安装pm2。 然后使用“ pm2 index.js”(相应地)启动程序。

每次对代码进行更改时,最好键入“ pm2 restart all”以应用更改