StackBlitz - ECONNREFUSED when connecting to local machine - express

I'm running a simple express server on my machine and attempting to ping it from a StackBlitz web container, but am getting the following error when trying to connect:
FetchError: request to https://192.168.1.23:8443/ failed, reason: connect ECONNREFUSED 192.168.1.23:8443
I've tried:
using https
allowing cors
setting up host: 0.0.0.0
Here's the code for the server, its a vanilla node project, just with express and cors.
var fs = require('fs');
var http = require('http');
var https = require('https');
var cors = require('cors')
var privateKey = fs.readFileSync('key.pem', 'utf8');
var certificate = fs.readFileSync('cert.pem', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var express = require('express');
var app = express();
app.use(cors())
app.get('/', (_, res) => res.send(`hello`));
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(8080, '0.0.0.0');
httpsServer.listen(8443, '0.0.0.0');
Here is the code for the stackblitz container, it is a vanilla node project with node-fetch:
import fetch from 'node-fetch';
const url = 'https://192.168.1.23:8443/';
const response = await fetch(url)
.catch((err) => console.error(err));
console.log(response?.status || 'failed');

Try use a html page to connect to your server. If still error then try embed an iframe in your html.

Related

http://localhost:500/socket.io not found error

Okay. I set up a socket.io system to get this error:
GET http://localhost:500/socket.io?EIO=4&transport=polling&t=<somevalue> 404 NOT FOUND
My client looks like this:
<script>
const socket = io()
</script>
And my server looks like this:
const server = require("http").createServer();
const app = express();
app.use("/", express.static("dist"));
const io = require("socket.io")(server);
io.sockets.on("connection", (socket) => {
console.log("new socket connection");
});
dist/index.html contains the script from earlier.
I tried various solutions, but they are not working :/
Does someone know why?
Use the app to create your http server:
const app = express();
const server = require("http").createServer(app);
app.use("/", express.static("dist"));
const io = require("socket.io")(server);
io.on("connection", (socket) => {
console.log("new socket connection");
});

Unable to Connect to Backend

Hello i am Trying to connect React-Native with Node.js using Fetch Api i tried many solutions i tried putting my IP address,localhost and 10.0.2.2 but nothing works i dont get any response back but when i change my code a little bit it gives me network failed request error.
React-Native Code:
//Sending Request to Node.js using Fetch API
await fetch("http://10.0.2.2:3000/studentSignup", {
//Setting Method
method:"POST",
//Setting Headers
headers:{
//Setting Content-Type
"Content-Type" : "application/json"
},
//Stringifying the email and password and storing it into body
body:JSON.stringify({
name,
gmail,
password,
retype
})
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
});
Node.js:
const express = require("express");
const app = express();
app.use("/studentSignup", (req,res,next)=>{
console.log("ok");
});
app.listen(3000);
lots of Mistakes
Full source code
var express = require('express')
var cors = require('cors')
var app = express()
var bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(jsonParser)
app.use(urlencodedParser)
app.use(cors())
app.post("/studentSignup", (req,res,next)=>{
console.log("ok");
});
app.listen(3000);
First of all, it's app.post not app.use
app.post("/studentSignup", (req,res,next)=>{
console.log("ok");
});
This might me due to cors
You can use this npm package to encounter this error cors
install cors in server folder
npm i cors --save
Usage
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.post("/studentSignup", (req,res,next)=>{
console.log("ok");
});
app.listen(3000);
Use body parser to handle incoming data from frontend
install body-parser in server folder
npm i body-parser --save
Usage
var express = require('express')
var cors = require('cors')
var app = express()
var bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(jsonParser)
app.use(urlencodedParser)
app.use(cors())
app.post("/studentSignup", (req,res,next)=>{
console.log("ok");
});
app.listen(3000);
So i was debugging and i thought that i have 2 ip's first one was Internet's ip and the second one was mine pc's ip and i was using internet's ip instead of my machine's ip so i changed the ip and that worked smoothly.

https settings for ionic app server settings

The application is build in MEAN stack and we are able to run the port successfully in 3001 port and our web application is running perfectly in HTTPS ... Now we have build the ionic app for the same application where we are using the same back up..
The ionic app is not logging in or form is not getting submitted..
Do we need to use a seperate port for the same application to use for ionic like
ionic in 8001
and web application (Angular) in 3001
What is the procedure to run the ionic app in SSL (https)
Any suggestion will be great helpful and thank you in advance
My code is as follows which worked perfectly:
var express = require('express');
var DataController = require('./user/DataController');
var UserController = require('./user/UserController');
var db = require('./database/database-db');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
// res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
// res.setHeader("Access-Control-Allow-Origin", "http://localhost:8100");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use('/user', UserController);
app.use('/data', DataController);
app.get('/', function(req, res){
res.send("Welcome to the secure mobile and web development world");
});
// This settings are for HTTPS, SSL web applications.
// var https = require("https");
// var fs = require("fs");
// var options = {
// key: fs.readFileSync("/home/path/ssl/keys/key.key"),
// cert: fs.readFileSync("/home/path/ssl/certs/crt.crt")
// };
// https.createServer(options,app).listen(3001);
// console.log('Welcome to the security world')
// This settings are only for HTTP sites
// var http = require("http");
// var fs = require("fs");
// http.createServer(app).listen(3001);
// console.log('Welcome to the security')
//This settings are for both HTTPS,HTTP SSL web applications.
var https = require("https");
var http = require("http");
var fs = require("fs");
var options = {
key: fs.readFileSync("/home/path/ssl/keys/key.key"),
cert: fs.readFileSync("/home/path/ssl/keys/crt.crt")
};
https.createServer(options,app).listen(3001);
console.log('Welcome to the security world')
http.createServer(app).listen(3002);
console.log('Welcome to the proxy world')

SSL settings for NODE application

My node application port is successfully running at https://www.example.com:3001 but I have the CORS issue while submitting the details
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.com:3001/user/findUser
NOTE: With out https, the application is running perfect but the SSL (https) is having an issue... Any help would be really appreciated
My code
//app.js used for configuring the application
const express = require('express'); //getting express module
const db = require('./database/database-db'); //Database connection file
const UserController = require('./user/UserController');
const DataController = require('./user/DataController');
const app = express();
const cors = require('cors');
app.use(function (req, res, next) {
// res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Origin', 'https://www.example.com');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
//importing UserController and it appears /user/allOtherURIs
app.use(cors());
app.use('/user', UserController);
app.use('/data', DataController);
app.get('/', function(req, res){
res.send('Welcome to MY-API');
});
//this should be exported because to make available all the imported modules in this file
module.exports = app;
'use strict' ;
//server.js for spinning up the node server on a specific port 3001
// var app = require('./app/app.js'); //making all the modules in app.js available
// var port = process.env.PORT || 3001 ; //setting port
// var server = app.listen(port, function(){
// console.log("Server is running on http://localhost:%s", port);
// });
//ssl port settings
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('key.key'),
cert: fs.readFileSync('cert.crt'),
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("Welcome");
}).listen(3001);
app.js code is:
Finally this is the code
var express = require('express');
var DataController = require('./user/DataController');
var UserController = require('./user/UserController');
var db = require('./database/database-db');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "https://www.example.com");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use('/user', UserController);
app.use('/data', DataController);
app.get('/', function(req, res){
res.send("Welcome");
});
// This settings are for HTTPS, SSL web applications
var https = require("https");
var fs = require("fs");
var options = {
key: fs.readFileSync("key.key"),
cert: fs.readFileSync("cert.crt")
};
https.createServer(options,app).listen(3001);
console.log('Welcome')
// // This settings are only for HTTP sites
// var http = require("http");
// var fs = require("fs");
// http.createServer(app).listen(3001);
// console.log('Welcome')

Koa HTTPS connection with koa-sslify module Without Reverse Proxy

I try to make HTTPS connection for Koa server with that module https://www.npmjs.com/package/koa-sslify but I get error "AssertionError: app.use() requires a generator function"
'use strict';
var app = require('application'),
enforceHttps = require('koa-sslify'),
config = require('config'),
fs = require('fs'),
path = require('path'),
routes = fs.readdirSync(path.join(__dirname, '../routing')).sort();
routes.forEach(function (route) {
require('../routing/' + route);
});
// Force HTTPS on all page
app.use(enforceHttps({
trustProtoHeader: true
}));
app.listen(config.server.port,config.server.host);
UPD:
I used NGINX instead, because probably it does that work better and use less resources
try in this way, but better use NGINX as a reverse proxy server
const Koa = require('koa');
const https = require('https');
const fs = require('fs');
const { default: enforceHttps } = require('koa-sslify');
const app = new Koa();
// Force HTTPS using default resolver
app.use(enforceHttps({
port: 443
}));
// index page
app.use(ctx => {
ctx.body = `hello world from ${ctx.request.url}`;
});
// SSL options
const options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
}
// start the server
https.createServer(options, app.callback()).listen(443);