Http2 not working with express - node.js

I have server.js file where is some code
var express = require('express')
var app = express()
var fs = require('fs');
app.get('/', function (req, res) {
res.send('hello, http2!')
})
var options = {
key: fs.readFileSync('./localhost.key'),
cert: fs.readFileSync('./localhost.crt')
};
require('http2').createServer(options, app).listen(8080);
After that I run in shell
$ node server.js
And server is waiting, but I can't open it. I tried http://localhost:8080 and https://localhost:8080 (I know that this is one is right one.). But nothing is going on, no errors no response in browser, what am I doing wrong? Also .key and .crt files not generated by me, I just copied it, can this be a problem?

At time of writing this, there are known issues with using node-http2 with express, see here: https://github.com/molnarg/node-http2/issues/100

Ok it wasn't http2 issue, just firefox doesn't want to open it.In chrome all works great on https://localhost:8080/.

Related

Basic express setup: not sending anything to local port

I created a frontend app and now trying to incorporate backend into it.
ON the same frontend app i added an index.js file in the root directory, and installed express and required it in index.js file.
Very basic setup as below:
const express = require('express')
const cors = require('cors')
const port = process.env.PORT || 3001
const app = express()
app.get('/', (req, res) => {
res.send({
greetings: 'hi'
})
})
app.listen(port, () => {console.log(`Server on port ${port}`)})
Server is successfully on port 3001 as per my terminal, however, on localhost:3001 I'm not seeing any json response I set up in app.get.
It says Cannot GET / instead. When i inspected in devtool(Network) it says 404.
This seems a very straightforward setup, but what could've gone wrong here?
i just figured why. I installed nodemon but my “start” script is “node index.js”. Should’ve used “nodemon index.js”
Working now with nodemon index.ks
Your code is fine, There are no errors, I tested it and it works as expected.
However few things to note, Keep Backend in Seperate folder/dirctory unless required.
Coming back to your question, There are many possiblity such as some modules are not installed properly
try running following command
//this will install if any library is currupt or not installed properly
npm i
if it doesn't work then try clearing cache
Also keep in mind, In nodeJS dev server does not automatically refresh changes, you need to restart server to see changes or you can use dev dependancy called Nodemon (this will auto restart server on saving changes)

When running script for express web server with node on windows get prompt to select app

I'm going through this this course currently.
There is a tutorial on how to configure and run express server. The following script is suggested:
var express = require('express');
var path = require('path');
var open = require('open');
var port = 3000;
var app = express();
app.get('/',function(req, res){
res.sendFile(path.join(__dirname,'../src/index.html'));
});
app.listen(port,function(err){
if(err){
console.log(err);
}
else{
open('localhost:'+port);
}
});
When I run it in project root with $ node buildScripts/srcServer.js I get a system prompt You'll need a new app to open this localhost with the only suggestion being look at windows store.
What's that about? What does it need an app for? In the course when the script is run the browser is opened, but it's on Mac there. When I navigate manually to localhost:3000 there is the error like there is supposed to be, but I'm somewhat concerned that this behavior will mess with live reloading so I'd like to get rid of it.
Add the http:// prefix and it will open using the default browser.
open('http://localhost:'+port);

Solving a Proxy Error (Node.js server)

Basically I get a 502 Proxy Error when running my node.js app.
Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /play.
Reason: Error reading from remote server
My server looks like this.
var express = require('express');
var https = require('https');
var http = require('http');
var path = require('path');
var fs = require('fs');
var mysql = require('mysql');
var app = express();
var options = {
key: fs.readFileSync('sslcert/keyfile.key', 'utf8'),
cert: fs.readFileSync('sslcert/crtfile.crt', 'utf8')
};
var httpsServer = https.createServer(options, app);
// stuff
httpsServer.listen(process.env.PORT);
I am really sorry if this is a noob question, actually I am still a beginner in things related to node.js. Thank you for your help!
Noël.
I just ran into the same problem. It's possible your problem was different, but in my case, the 502 error was coming from Apache. My httpd.conf file was referencing the same 2 certificate files that my node app was referencing.
Instead of using
var httpsServer = https.createServer(options, app);
try just
app.listen(3000);
I'm not sure exactly why it wasn't working. My theory is the node app was using these cert files, and apache was unable to access them, and thus creating this situation. However, just using a normal express app fixed the problem for me.
I hope this helps somebody!

How to enable SSL connection a NodeJS (Express) based Server

Following is the script I found on NodeJS Official Website:
// curl -k https://localhost:8000/
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
I'm completely new to SSL thing. I read some tutorials on how to enable SSL on Nodejs but still quite not confident with the process.
I have a domain name (Godaddy), SSL (Namecheap) and Cloud Server (Digital Ocean with an application deployed on HTTP prefix).
Whenever I open my Login page of my website, Google Chrome mark it as "Not secure" so I wanted to add SSL to the website.
What things I need to do on the NodeJS server (Express) and what things I need to do on Namecheap? What will be the sequence of doing that? What are cmd lines to generate .pem .csr files?
I'm didn't found and comprehensive guide laying down all the steps in a concise manner so just laid down the steps concisely (if possible) with the links to the resources for further digging.
And also, how can I use express framework to create https server in liue of above script?
That script is correct for setting the certs for your https. If your site is public, as it seems, then you'll want to buy certs from your ssl service, Namecheap in your example. Then you would move them to your host and reference them in the options object in your example. However, you can generate your own ssl certs and that will work as well. Though, any users will be warned that they're not trusted since you self signed/created them. I suggest going with the Namecheap option.
Note: You only have an https server in your example and anyone attempting to access your site via http will receive a blank page. You'll need to also create an http server, via the following:
var http = require('http');
http.createServer(...);
I would suggest having the http server simply redirect to the https url.
My code and error is here:
no such directory found error:
key: fs.readFileSync('../private.key'),
cert: fs.readFileSync('../public.cert')
error, no such directory found
key: fs.readFileSync('./private.key'),
cert: fs.readFileSync('./public.cert')
Working code should be
key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
Complete https code is:
const https = require('https');
const fs = require('fs');
// readFileSync function must use __dirname get current directory
// require use ./ refer to current directory.
const options = {
key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
};
// Create HTTPs server.
var server = https.createServer(options, app);
This is my working code for express 4.0.
express 4.0 is very different from 3.0 and others.
4.0 you have /bin/www file, which you are going to add https here.
"npm start" is standard way you start express 4.0 server.
readFileSync() function should use __dirname get current directory
while require() use ./ refer to current directory.
First you put private.key and public.cert file under /bin folder,
It is same folder as WWW file.

serveStatic() unable to locate a file

I am new to node.js, and I am trying to use the serveStatic function to locate a specific file.
When I specify the exact path in the argument it doesn't work. However it works only when I specify the directory only , and name the file index.html inside that directory.
Any idea on how I can use to it locate a specific file? Any help would be really appreciated from you guys thanks!
Below is my code
var connect = require('connect'),
http = require('http'),
serveStatic = require('serve-static');
var app = connect();
// app.use(serveStatic('public')); Works
app.use(serveStatic('public/test.html'));// doesn't work
app.use(function(req, res){
});
http.createServer(app).listen(3000);
serve-static is meant to serve a whole directory (with all sub-directories, if any). You can't use it to serve just one single file.
What you could do with serve-static is to set a default file to be sent when user requests a root of your directory (by default it's an index.html file):
app.use(serveStatic('public', {index: 'test.html'}));
But if you really want to send just a single file, then is's better to use this answer:
app.use(function(req, res) {
res.sendfile('test.html', {
root: __dirname + '/public/'
});
});
Though, the best possible solution is to read this file once and cache it. In this case there will be no need to access your storage device each time somebody is requesting this file:
var html_data = require('fs').readFileSync('./public/test.html');
app.use(function(req, res) {
res.send(html_data);
});

Resources