在Azure上部署Nodej但获取404

时间:2017-07-13 09:02:18

标签: node.js azure express routing

我最近为自己构建了一个基于join()的网络应用。我通过了所有本地测试,但是当我将它部署到Azure时,它会继续显示404。 这是网络:MEAN

我认为主要的问题是路由。似乎Azure无法找到我的api.js文件。

我已经阅读了所有可能的资源,似乎是app.js下的问题。

这是我的app.js文件:

    //process.chdir(__dirname);

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var bcrypt = require('bcrypt');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
//global.passport = passport;
var session = require('express-session');
var mongoose = require('mongoose');                         //add for Mongo support
var models = require('./models/models.js');
//mongoose schemas
if(process.env.DEV_ENV){
    mongoose.connect('mongodb://localhost/MylocalDB', {useMongoClient: false}); 
} else {
    mongoose.connect('mongodb://xxxx:xxxxxx@xxxxxxxx/myweb', {useMongoClient: false});
    //mongoose.connection.openUri('mongodb://xxxxx:xxxx@xxxxx/myweb'); 
}
            //connect to Mongo

//import the routers
var index = require('./routes/index');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(session({
  secret: 'keyboard cat'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());

//register routers to root paths
app.use('/', index);
app.use('/api', api);
app.use('/auth', authenticate);

//// Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

1 个答案:

答案 0 :(得分:0)

讨论了类似的问题here

在Azure Web Apps上运行的Node.js应用程序通过IISNode托管在IIS上。因此,在IIS上配置应用程序需要web.config文件。如果您通过Continuous Deployment将应用部署到Azure App Service,则Azure将自动生成web.config文件。或者您可以从here下载文件。

以下是Azure Web Apps上用于node.js应用程序的默认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 app.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

               To debug your node.js application:
                 * set the debuggingEnabled option to "true"
                 * enable web sockets from the portal at https://manage.windowsazure.com/#Workspaces/WebsiteExtension/Website/aarontestnode/configure
                 * browse to https://aarontestnode.azurewebsites.net/app.js/debug/

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

如果您仍然遇到问题,可能需要查看How to debug a Node.js web app in Azure App Service以进行问题排查。