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
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!!
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 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')
I'm having difficulty with getting CORS to work. I'm trying to fetch data from a Heroku app I set up. I'm fetching from Redux, and using ExpressJS for the backend. I've been looking through the CORS docs but still can't figure it out. enter link description here
This is how it looks in Express
var express = require('express');
var router = express.Router();
var cors = require('cors')
router.options('/', cors())
router.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
router.get('/', cors(), function(req, res, next) {
res.json({...})
}
I have the proxy set up in my app to http://localhost:3001/, but my app is running on 3000. I'm including this in case it could be the issue, but I don't know that it is.
My Redux file is set up like this
return dispatch => {
const url = "https://app-name.herokuapp.com/users";
return fetch(url, {
method: 'GET',
mode: 'cors',
headers: { 'Content-Type': 'text' }
})
The full error is: "Failed to load https://app-name.herokuapp.com/users: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access."
var express = require('express');
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,POST");
// res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
I'm trying to set cookie using res.cookie or res.append('Set-Cookie',...) on express.js, but when I use req.cookies, it return {}(which is the default value of res.cookies). I've searched many web pages but it still can't return the right value. PS: Express is 4.15.2
in server.js:
var express = require('express');
var session = require('express-session');//设置session
var cookieParser = require('cookie-parser');//解析cookie
var bodyParser = require('body-parser');
var app = express();
app.use(express.static('public'));
app.use(session({
secret: 'keyboard cat',
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: true
}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
// 查询所有博客数据
app.get('/getAll',function(req,res){
var pageNum = req.query.pageNum;
//连接数据库
query("some sql",function(err,vals,fields) {
console.dir(req.session.id);
// Cookies that have not been signed
console.log('Cookies: ', req.cookies)
// Cookies that have been signed
console.log('Signed Cookies: ', req.signedCookies)
res.send(vals);
});
});
//登陆验证
app.post('/login',function(req,res){
var username = req.body.username;
var password = req.body.password;
//过滤
var sql = "some sql";
query(sql,function(err,vals,fields) {
if(vals.length == 1){
//登录成功
//res.cookie('mycookie', '1234567890', { domain:'localhost',secure:false, maxAage:120000, httpOnly: true });
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
// req.cookie('sid',req.session.id,{ maxAge: 900000, httpOnly: false});
res.send("ok");
}else{
//登陆失败
res.send("false");
}
});
});
app.get('/', function (req, res) {
res.sendFile( __dirname + "/"+ "index_prod.html" );
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
When I login in, the result is as following:
cookie
but when I request for /getAll ,the console for cookies are: { }. (the default value, NOT the value we just write).
If the cookies and session have been correctly used, the reasons may be :
Make sure the client and the server obey the Same-origin policy. If not, make some changes.
Make sure your websites have no errors. (In the code above, there exit other errors such as 404 (Not Found) in the process of images fetching)