Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js azure应用程序服务中的cosmosdb连接失败_Node.js_Azure_Azure Web App Service_Azure Cosmosdb_Azure Cosmosdb Mongoapi - Fatal编程技术网

Node.js azure应用程序服务中的cosmosdb连接失败

Node.js azure应用程序服务中的cosmosdb连接失败,node.js,azure,azure-web-app-service,azure-cosmosdb,azure-cosmosdb-mongoapi,Node.js,Azure,Azure Web App Service,Azure Cosmosdb,Azure Cosmosdb Mongoapi,当我在开发时,我可以连接到cosmodb没有问题,但是当我将其部署到azure应用程序服务时,应用程序服务中的日志流显示cosmodb连接失败。我正在使用环境变量,所以我认为这是问题所在,特别是因为azure没有将.env文件复制到site/wwwroot,所以我转到应用程序设置并设置连接所需的每个env变量的值,但仍然失败 作为一个实验,我还尝试使用一个硬编码的连接字符串来连接本地工作的mongodb atlas,但在部署到应用程序服务时也失败了。也许问题出在server.js中的端口。第一次

当我在开发时,我可以连接到cosmodb没有问题,但是当我将其部署到azure应用程序服务时,应用程序服务中的日志流显示cosmodb连接失败。我正在使用环境变量,所以我认为这是问题所在,特别是因为azure没有将.env文件复制到site/wwwroot,所以我转到应用程序设置并设置连接所需的每个env变量的值,但仍然失败

作为一个实验,我还尝试使用一个硬编码的连接字符串来连接本地工作的mongodb atlas,但在部署到应用程序服务时也失败了。也许问题出在server.js中的端口。第一次部署到云,所以我是一个noob。我非常感谢你的帮助

020-02-20T23:37:00.887948933Z: [INFO]  2020-02-20T23:37:00: PM2 log:  Use `pm2 show <id|name>` to get more details about an app
2020-02-20T23:37:00.888703339Z: [INFO]  2020-02-20T23:37:00: PM2 log: [--no-daemon] Continue to stream logs
2020-02-20T23:37:00.897860809Z: [INFO]  2020-02-20T23:37:00: PM2 log: [--no-daemon] Exit on target PM2 exit pid=58
2020-02-20T23:37:06.517883906Z: [INFO]  23:37:06 0|server  | BLOB/home/site/wwwroot
2020-02-20T23:37:07.340932229Z: [INFO]  23:37:07 0|server  | (node:69) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
2020-02-20T23:37:07.529169475Z: [INFO]  23:37:07 0|server  | (node:69) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
2020-02-20T23:37:07.912008216Z: [INFO]  23:37:07 0|server  | Connection on Failed

我尝试测试我的express应用程序以将我的cosmos db mongo api与mongoose连接。我没有使用PM2管理我的express应用程序。您可以尝试测试我的以下代码以排除网络问题

请查看我的app.js:

mongo.js:

web.config:



我猜是网络层的某些东西正在阻止你的应用程序中mongo客户端使用的端口,因为这在Cosmos或Atlas中发生。也许可以检查你的网络应用的网络设置。
const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");

var env = require("dotenv").config();


const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};

mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMOSDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);

var server = app.listen(app.get("port"), function() {
  debug("Express server listening on port " + server.address().port);
});
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/mongo');

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);

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('/mongo', 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'));
          });
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();

var url = "mongodb://jaygongmongo:*******==@jaygongmongo.mongo.cosmos.azure.com:10255/?ssl=true&appName=@jaygongmongo@";

/* GET users listing. */
router.get('/', function(req, res, next) {

  new mongoose.connect(url+'/db', {
  useNewUrlParser: true,
  useUnifiedTopology: true
    })
   .then(() => res.send("Connection to CosmosDB successful"))
  .catch(err => res.send(err));
});

module.exports = router;
<?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>