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')
Related
I have an express server serving react pages. I am trying to show the work to a client via a ngrok tunnel. But whenever I try to log in at the ngrok URL for my server it fails to connect back to my localhost where the express routes for auth are.
I feel like it's a simple error I'm making. The browser is trying to make a request to the express server at localhost:5000, but there is nothing at localhost on my client's network.
This is my app.js
const createError = require('http-errors');
const express = require('express');
const debug = require('debug')('app');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
require('dotenv').config()
const ensureToken = require('./middleware/ensureToken');
const path = require('path');
const app = express();
const { init } = require('./utils/cron/createCron');
const cors = require('cors')
// Routers
const authRouter = require('./routes/auth')
const botRouter = require('./routes/bot')
const proxyRouter = require('./routes/proxy');
const winstonLogger = require('./utils/log/logger');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
const whiteList = ['http://localhost:3000/', 'http://localhost:3000']
const corsOptions = {
origin: (origin, callback)=>{
if (whiteList.indexOf(origin) !== -1){
callback(null, true)
}else{
callback(new Error('Not Allowed by CORS'))
}
optionsSuccessStatus:200
}
}
// app.use(cors(corsOptions))
app.use(cors({ credentials: true, origin: true }))
app.use(express.static(path.join(__dirname, 'build')));
// Base Routes
app.use('/api/auth', authRouter);
app.use(ensureToken) //Add this before routes that need to be protected ny valid token
app.use('/api/bot', botRouter);
app.use('/api/proxy', proxyRouter);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
// 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');
});
app.listen(process.env.PORT, ()=>{
winstonLogger.info(`Listening on ${process.env.PORT}`)
debug(`Listening on ${process.env.PORT}`);
console.log(`Listening on ${process.env.PORT}`);
init()
})
module.exports = app;
Any help is appreciated!!
whats wrong with my code? its showing no results....although it kinda works when i use google.com as url but in other cases it shows no results*I haven't shared my api key here(appid=)
const express = require('express');
const app = express();
const http = require('http');
app.get("/", function(req, res) {
const url= 'https://api.openweathermap.org/data/2.5/weather?q=london&appid='
http.get(url, function(response){
console.log(response);
// response.on("data", function(data){
// const weatherData = JSON.parse(data);
// const temp = weatherData.main.temp;
// // const weatherDescription = weatherData.weather[0].description;
// res.send(temp)
// })
// res.send('server is sending');
})
})
app.listen(3000, function(req, res){
console.log('Server is alive')
})
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')
My node applications runs fine with http but in https it throws cors error and my ssl port link (https://www.example.com:3001) works fine and loads.. So ssl settings are fine but the cors issue is not allowing to submit the form..
The following is the code for http which is working fine.. Can anyone check and fix the issue..
var express = require('express');
var DataController = require('./user/DataController');
var UserController = require('./user/UserController');
var db = require('./database/dbbase-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");
});
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.listen(3001, function () {
// console.log('Welcome')
// })
Finally it worked and here is the updated 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')
Check ports if there is firewall rules or there's other listing on the the same port
I'm trying to create a really simple node API using express.js 4 but I need a few 'realtime' events for which I added socket.io. I'm fairly new to both so I'm likely missing something basic but I can't find good docs/tuts on this.
In the express app (created with the express generator) I have something like this based on simple examples and project docs that I read. This works OK and from client apps, I can send/receive the socket events:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var api = require('./routes/api');
var app = express();
var io = require('socket.io').listen(app.listen(3000));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', api);
io.sockets.on('connection', function (socket) {
console.log('client connect');
socket.on('echo', function (data) {
io.sockets.emit('message', data);
});
});
// error handlers omitted
module.exports = app;
but I want to use the sockets from my API routes (in the ./routes/api.js file that I 'require' above). For example, someone might use the API to PUT/POST a resource and I want that broadcast to connected socket.io clients.
I cannot see how to use the 'io' variable or organise the code currently in the io.sockets.on('connection' ... function inside express routes. Here's the ./routes/api.js file:
var express = require('express');
var router = express.Router();
var io = ???;
router.put('/foo', function(req, res) {
/*
do stuff to update the foo resource
...
*/
// now broadcast the updated foo..
io.sockets.emit('update', foo); // how?
});
module.exports = router;
One option is to pass it in to req object.
app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var api = require('./routes/api');
var app = express();
var io = require('socket.io').listen(app.listen(3000));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
io.sockets.on('connection', function (socket) {
console.log('client connect');
socket.on('echo', function (data) {
io.sockets.emit('message', data);
});
});
// Make io accessible to our router
app.use(function(req,res,next){
req.io = io;
next();
});
app.use('/api', api);
// error handlers omitted
module.exports = app;
./routes/api.js:
var express = require('express');
var router = express.Router();
router.put('/foo', function(req, res) {
/*
do stuff to update the foo resource
...
*/
// now broadcast the updated foo..
req.io.sockets.emit('update', foo);
});
module.exports = router;
I've modified your files a little bit, may you check if it works?
You can pass the io you've defined to your routes like below;
require('./routes/api')(app,io);
I didn't test the Socket.IO parts but there is no syntax error and routes also working.
server.js file:
var express = require('express');
var app = express();
var path = require('path');
var logger = require('morgan');
var io = require('socket.io').listen(app.listen(3000));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
io.sockets.on('connection', function (socket) {
console.log('client connect');
socket.on('echo', function (data) {
io.sockets.emit('message', data);
});
});
require('./routes/api')(app,io);
console.log("Server listening at port 3000");
api.js:
module.exports = function(app,io) {
app.put('/foo', function(req, res) {
/*
do stuff to update the foo resource
...
*/
// now broadcast the updated foo..
console.log("PUT OK!");
io.sockets.emit('update'); // how?
res.json({result: "update sent over IO"});
});
}
Supposing you want to access the SocketIO from anywhere in your application, not just in the router, you could create a singleton for it. This is what works for me:
//socket-singletion.js
var socket = require('socket.io');
var SocketSingleton = (function() {
this.io = null;
this.configure = function(server) {
this.io = socket(server);
}
return this;
})();
module.exports = SocketSingleton;
Then, you need to configure it using your server:
//server config file
var SocketSingleton = require('./socket-singleton');
var http = require('http');
var server = http.createServer(app);
SocketSingleton.configure(server); // <--here
server.listen('3000');
Finally, use it wherever you want:
//router/index.js
var express = require('express');
var router = express.Router();
var SocketSingleton = require('../socket-singleton');
/* GET home page. */
router.get('/', function(req, res, next) {
setTimeout(function(){
SocketSingleton.io.emit('news', {msg: 'success!'});
}, 3000);
res.render('index', { title: 'Express' });
});
module.exports = router;
One more option is to use req.app.
app.js
const express = require('express');
const path = require('path');
const logger = require('morgan');
const api = require('./routes/api');
const app = express();
const io = require('socket.io').listen(app.listen(3000));
// Keep the io instance
app.io = io;
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
// ...
app.use('/api', api);
module.exports = app;
routes/api.js
const express = require('express');
const router = express.Router();
router.put('/foo', function(req, res) {
/*
* API
*/
// Broadcast the updated foo..
req.app.io.sockets.emit('update', foo);
});
module.exports = router;
Refactored Edudjr's answer.
Change the singleton to create a new instance of socket.io server
const { Server } = require('socket.io');
const singleton = (() => {
this.configure = (server) => this.io = new Server(server)
return this
})();
module.exports = singleton
Initialise your express app, the server and the singleton.
// initialise app
const app = express();
const server = require('http').createServer(app);
// configure socket.io
socket.configure(server)
Then in your router
const socket = require('/utils/socket-singleton');
socket.io.emit('event', {message: 'your message here'})
I think best way is to set io as a property of req, like below:
app.use(function(req,res,next){
req.io = io;
next();
});
app.use('/your-sub-link', your-router);