簡體   English   中英

無法將Node JS部署運行到Azure

[英]Can't run Node JS Deployment to Azure

我遵循了本教程:

https://docs.microsoft.com/zh-cn/azure/app-service/app-service-web-get-started-nodejs

我已經使用“ Zip Deploy”工具部署了Express JS應用程序:

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

當我嘗試調用公共API時,總是出現錯誤消息:“ 您要查找的資源已被刪除,名稱已更改或暫時不可用。

奇怪的是,我的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> 

我使用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;

訪問結果:

在此處輸入圖片說明

您可以檢查差異。有任何問題,請告訴我。

我的解決方案: 不要遵循教程/博客文章

我使用了Visual Studio 2017,並找到了一個名為``基本Azure Node.js Express 4 App''的項目模板。 基礎項目進行得很順利,僅花費了5分鍾即可完成設置。

部署nodejs的最簡單方法是使用終端。

您只需像在普通計算機上一樣將項目克隆到服務器即可。 執行“ npm install”通過“ npm start”或“ node index.js”運行項目(取決於您的文件名)。 檢查程序是否在服務器中啟動,最好使用郵遞員測試api是否正常工作。 如果有錯誤,請修復它們。 如果不是,請在服務器計算機上安裝pm2。 然后使用“ pm2 index.js”啟動程序(相應地)。

每次對代碼進行更改時,最好鍵入“ pm2 restart all”以應用更改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM