HTTPS issues in azure - node.js

I imported the git socket.io chat room project! The code works normally with http = require ('http') but when exchanging for https = require ('https') my server responds with error 500 http
var express = require('express')
, app = express()
// , http = require('http')
, https = require('https')
, fs = require('fs')
, privateKey = fs.readFileSync('HTTPS_Permissions/key.key', 'utf8')
, certificate = fs.readFileSync('HTTPS_Permissions/cert.cert', 'utf8')
, credentials = {key: privateKey, cert: certificate}
, httpsServer = https.createServer(credentials, app)
// , httpServer = http.createServer(app)
, io = require('socket.io').listen(httpsServer)
//, port = process.env.PORT || 8080
, port = process.env.PORT
httpsServer.listen(port, function () {
console.log('Server listening on port %d', port);
});
//httpServer.listen(port);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});

I followed the project you shared in the comment,it works on my side.
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>
If you throw the index.html into public folder which is created by yourself under wwwroot/ directly, you need to add the below code into your code based on this article.
app.use(express.static('public'))
I tested for that.
Update Answer:
I also turn on the Web Sockets Option.

Related

HTTP ERROR 400.605. Deploying NodeJS app on IIS

I've got error during deploying my app to IIS Server. I use URL Rewrite and IISNode. I gave all permissions to IUSR and IIS_IUSRS, and I went throught a lot of errors, but I can't go through this one. I will be very grateful for your help.
I've got this error
My web.config file looks like:
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="src/app.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules>
<rule name="app">
<match url="/*" />
<action type="Rewrite" url="src/app.js" />
</rule>
<rule name="ReverseProxyInboundRule1" stopProcessing="true">
<match url="(.*)" />
<action type="Rewrite" url="http://localhost:8080/{R:1}" />
</rule>
</rules>
</rewrite>
<security>
<requestFiltering>
<hiddenSegments>
<add segment="node_modules" />
</hiddenSegments>
</requestFiltering>
</security>
</system.webServer>
</configuration>
My app.js file looks like:
const express = require('express');
const cors = require('cors');
const app = express();
app.get('/', (req, res, status)=>{
return res.status(200).json({
"message": "Hello world!"
});
});
app.use(cors());
app.use(express.json());
app.listen(8080, () => {
console.log('App listening on port 8080')
});
From the analysis of the error information, it can be determined that the problem is caused by the abnormal request of the ARR module, mainly because of the syntax error of the URL rewriting rule, which will cause this 400.605 error. It is recommended to use the exclusion method, first disable all ARR rules, and then gradually sort out the rules with grammar problems.
Here is the same question you can use as a reference: ARR The request cannot be routed because it has reached the Max-Forwards limit. The server may be self-referencing itself in request routing topology.

Hosting node js website to Azure. Default path / not working

I have a node js website which I am deploying to the azure server using visual studio code. The following is my code at server.js
var express =require('express');
var bodyParser=require("body-parser")
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var nodemailer = require("nodemailer");
var port=process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
console.log('hello from server');
res.render('./public/index.html');
});
I deployed the website to an azure app service and the url always expects the index.html to be added to it to work. for e.g https://abc.azurewebsites.net does not work but https://abc.azurewebsites.net/index.html works. How do I remove the index.html from the url?
My azure folder structure is site/wwwroot/public/all html files.
Can anyone please suggest a solution
Update:
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<webSocket enabled="false" />
<rewrite>
<rules>
<rule name="DynamicContent">
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
</conditions>
<action type="Rewrite" url="public/index.html"/>
</rule>
</rules>
</rewrite>
<security>
<requestFiltering>
<hiddenSegments>
<remove segment="bin"/>
</hiddenSegments>
</requestFiltering>
</security>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
</configuration>
Original Answer:
Just add a file named .htaccess to the root directory('/site/wwwroot'), and this is the content of the file:
DirectoryIndex public/index.html
After that, default of your web app will change to 'public/index.html'.

Server-sent Events not working with Window App Service in Azure

I've tried to get the following code running on a Windows App Service on Azure:
const http = require('http');
const server = http.createServer((request, response) => {
response.setHeader('Content-Type', 'text/event-stream');
response.setHeader('Cache-Control', 'no-cache');
response.setHeader('Connection', 'keep-alive');
response.setHeader('Transfer-Encoding', 'chunked');
response.flushHeaders();
var interval = setInterval(function () {
response.write("data: extra data\n\n");
}, 1000);
request.on('close', function () {
clearInterval(interval);
})
});
const port = process.env.PORT || 1337;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
It works when I run it locally, however does not when deployed to the App Service.
My web.config looks like as follows:
<?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" responseBufferLimit="0"/>
</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{PATH_INFO}"/>
</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"/>-->
<iisnode flushResponse="true" />
</system.webServer>
</configuration>
I've added in <iisnode flushResponse="true" /> and responseBufferLimit="0" as per suggestions from the Microsoft App Service docs: https://learn.microsoft.com/en-us/azure/app-service/app-service-web-nodejs-best-practices-and-troubleshoot-guide#flushresponse but still to no avail.
Your project can run locally, that is, through the command line npm start, npm run dev, etc. to start webapp in local. At this time, the web.config file will not be used. Unless you deploy the project in the local IIS, IIS will recognize the web.config file.
Assuming that there is no problem with your project, I think you can delete your web.config file first (must be backed up). Then use git to deploy, and then through kudu, find the web.config automatically generated by the deployment (also needs to be backed up, because subsequent operations will modify the source file, if the modification is wrong, you can restore it).
A post about git deployment to automatically generate web.config.
Compare the difference between the web.config content in your current project and the automatically generated git deployment, and add the functions and content you want, such as flushResponse="true",responseBufferLimit="0".
If something goes wrong, remember to restore the backup file. This can be used for troubleshooting.

host nodejs chat application with iis node

I have developed a chat application with nodejs. Currently, I am using the chat server hosted from a command prompt. This chat server is not bound to any domain name. I want it to bind to a domain with IIS. I have also tried to install IIS Node but could not get through. I have all my chat code in chatroom.js file, there is no HTML file to be rendered. I am not clear how to host it with IIS Node. I am using IIS 8 on Windows 8. The error I am get when hit the URL : http://localhost:3004/chatRoom.js
HTTP Error 500.21 - Internal Server Error
Handler "iisnode-socketio" has a bad module "iisnode" in its module list
Below is my web.config :
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.webServer>
<!-- indicates that the server-faye.js and server-socketio.js files are node.js applications
to be handled by the iisnode module -->
<handlers>
<add name="iisnode-socketio" path="chatRoom.js" verb="*" modules="iisnode" />
</handlers>
<!-- indicate that all strafic the URL paths beginning with 'socket.io' should be
redirected to the server-socketio.js node.js application to avoid IIS attempting to
serve that content using other handlers (e.g. static file handlers)
-->
<globalModules>
<add name="iisnode" image="C:\Program Files (x86)\iisnode-express\iisnode.dll" />
</globalModules>
<rewrite>
<rules>
<clear />
<rule name="cdw">
<match url="/*" />
<action type="Rewrite" url="chatRoom.js" />
</rule>
</rules>
</rewrite>
<!-- disable the IIS websocket module to allow node.js to provide its own
WebSocket implementation -->
<webSocket enabled="false" />
</system.webServer>
</configuration>
node server side code looks as follows :
var express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server),
Room = require('./room.js'),
defaultValues = require('./default.js'),
_ = require('underscore')._;
var request = require('request');
//require('request').debug = true; // uncomment for debugging
app.use('/', express.static(__dirname + '/public'));
server.listen(process.env.PORT);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/indexroom.html')
});
Please let me know if I am missing anything.

How to specify a file path in handler tag in web.config

I am trying to run a simple node.js application on Azure cloud.
I basically followed the instruction written in the following websites.
-Creation of Web application-
https://code.visualstudio.com/tutorials/app-service-extension/create-app
-Deployment of Web application-
https://code.visualstudio.com/tutorials/app-service-extension/deploy-app
In order to run it on Azure(IIS), I added web.config and server.js in the root folder as below.
added 2 files
The contents of the files are as follows.
[web.config]
<configuration>
<system.webServer>
<handlers>
<!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
</handlers>
<rewrite>
<rules>
<!-- All URLs are mapped to the node.js site entry point -->
<rule name="DynamicContent">
<match url="/*" />
<action type="Rewrite" url="server.js"/>
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
[server.js]
The below shows only a part of the codes.
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('./app');
var debug = require('debug')('myexpressapp:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
After deployed to Azure(IIS), the web application successfully ran. However, I would like to use the bin/www file instead of server.js. Actually, I created the server.js file in the root folder by coping the bin/www file.
In order to directly use bin/www, I changed the web.config as follows, but this leads to an error. The browser shows the error;"The resource you are looking for has been removed, had its name changed, or is temporarily unavailable." It seems that it cannot find the www file. Am I wrong with how I write the path?
<configuration>
<system.webServer>
<handlers>
<!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="bin/www" verb="*" modules="iisnode"/>
</handlers>
<rewrite>
<rules>
<!-- All URLs are mapped to the node.js site entry point -->
<rule name="DynamicContent">
<match url="/*" />
<action type="Rewrite" url="bin/www"/>
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
I would appriciate any help.
I was able to solve the problem.
I changed the name of the folder from "bin" to some other name and it worked. I am trying to understand why the name "bin" does not work though...Is it because "bin" is kind of reserved by server and it can not be used? I would appriciate it if someone could let me know any possible reasons...

Resources