Node.js server gives Cross-Origin Request Blocked - javascript

My Node.js server code is running on an AWS instance. It looks like this:
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var logger = require('morgan');
var cors = require('cors');
var SuperLogin = require('superlogin');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var config = {
dbServer: {
protocol: 'http://',
host: 'localhost:5984',
user: '',
password: '',
userDB: 'sl-users',
couchAuthDB: '_users'
},
mailer: {
fromEmail: 'gmail.user#gmail.com',
options: {
service: 'Gmail',
auth: {
user: 'gmail.user#gmail.com',
pass: 'userpass'
}
}
},
security: {
maxFailedLogins: 3,
lockoutTime: 600,
tokenLife: 86400,
loginOnRegistration: true,
},
userDBs: {
defaultDBs: {
private: ['supertest']
}
},
providers: {
local: true
}
}
// Initialize SuperLogin
var superlogin = new SuperLogin(config);
// Mount SuperLogin's routes to our app
app.use('/auth', superlogin.router);
app.listen(app.get('port'));
console.log("App listening on " + app.get('port'));
I am using an ionic 2 App that makes PUT calls to the Node.js server running on port 3000. When running the App in the browser on my laptop (using ionic serve) the PUT call gives the CORS error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://ec2-xx-xxx-xx-4xx.eu-central-1.compute.amazonaws.com/auth/login.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
As far as I can tell the server code is setup to allow all origins but I am getting this error nonetheless.

This is because the preflight is triggered, which means that an OPTIONS request will arrive at your server. This is well explained at
this description by MDN as pointed out by #johannes merz in the comments to your question.
You can instruct your server to accept it by rep something like this:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if ('OPTIONS' == req.method) {
res.sendStatus(200);
}
else {
next();
}});

Related

Cors-Problem when running a local node application

I simply want to POST data from a js-script to a node-server application which i run with express.
When sending the data i get: CORS-Header 'Access-Control-Allow-Origin' does not match with 'localhost:3000'.
Client-Script:
let url = 'http://localhost:3000/api'
const options = {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: jsonData,
};
fetch(url, options)
Server-Script:
const express = require('express');
const app = express()
app.listen(3000, () => console.log('Listening at 3000'))
app.use(express.static(__dirname))
const cors = require("cors")
app.use(cors({ origin: 'localhost:3000' }));
app.post('/api', (request, response) => {
console.log(request)
})
If i open the network-analyzer from Firefox, this is what i get:
fetch
How can i solve this issue?!
Thanks a Lot,
Max
Use this extension for local development
Allow CORS: Access-Control-Allow-Origin
If you add:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
it works just fine!
src: https://dzone.com/articles/cors-in-node
I think app.use(cors({ origin: 'localhost:3000' })); should be app.use(cors({ origin: 'http://localhost:3000' }));
https://github.com/expressjs/cors#configuring-cors

how to remove cors error while using ajax request?

I am trying to make session using express-session with passport in cross domain .I take help of following links
Sending credentials with cross-domain posts?
Passport js fails to maintain session in cross-domain
**I am getting below error**
Failed to load http://localhost:5000/users/login: Response to
preflight request doesn't pass access control check: The value of the
'Access-Control-Allow-Origin' header in the response must not be the
wildcard '*' when the request's credentials mode is 'include'. Origin
'http://localhost:3000' is therefore not allowed access. The
credentials mode of requests initiated by the XMLHttpRequest is
controlled by the withCredentials attribute.
here is my whole code
https://github.com/naveennsit/Cors
client index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="style/style.css" rel="stylesheet" type="text/css"/>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="jquery.js"></script>
</head>
<body>
<script>
$(function () {
$.ajax({
url: 'http://localhost:5000/users/login',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({id: 5}),
dataType: 'json',
xhrFields: {
withCredentials: true,
},
crossDomain: true,
success: function () {
console.log('success');
},
error: function () {
console.log('error')
}
});
})
</script>
</body>
</html>
server code
server.js
var app = require('./app');
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`app is running on ${PORT}`);
})
app.js
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const path = require('path');
const morgan = require('morgan');
const cors = require('cors');
const session = require('express-session');
const passport = require('passport');
const app = express();
// Middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cookieParser());
app.use(cors());
app.use(cookieParser());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
next();
});
app.use(session({
secret: 'secret',
resave: false,
domain: '.localhost:3000',
saveUninitialized: false,
cookie: {
domain: '.localhost:3000',
maxAge: 24 * 6 * 60 * 10000
},
}))
app.use(passport.initialize());
app.use(passport.session());
//Routes
app.use('/users', require('./routes/user.route'))
module.exports = app;
controller.js
const passport = require('passport');
const passportConfig = require('../passport')
module.exports = {
login: async (req, res, next) => {
console.log(req.body);
try {
req.login(req.body.id, function () {
res.json({message: "Registration successfully"});
})
} catch (e) {
console.log(e)
}
},
}
passport.js
const passport = require('passport');
passport.serializeUser(function(id, done) {
console.log('ddd');
// console.log(user);
done(null, id);
});
passport.deserializeUser(function(id, done) {
console.log('deserializeUser');
done(null, id);
// db.User.findById(id, function (err, user) {
// done(err, user);
// });
});
routes
const express = require('express');
const router = require('express-promise-router')();
const controller = require('../controllers/user.controller');
router.route('/login',)
.post(controller.login)
module.exports = router;
I want to add session in cross-domain.I already apply cors plugin still getting same error
The easiest way is to use the node.js package cors. The simplest usage is:
var cors = require('cors')
var app = express();
app.use(cors());
When using withCredentials: true in ajax, cors need to configure as below.
app.use(cors({origin: 'http://localhost:3000', credentials: true}));
You are almost there to solve it. You need to send actually allowed host in Access-Control-Allow-Origin header value and not *
If you want to allow for all origins, then you can include req.headers.origin for Access-Control-Allow-Origin header value in your CORS middleware:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
next();
});

Node JS Express Server - Cross Origin Request Blocked, even with all the correct headers

Despite having the correct headers in my nodejs server:
app.get('/api', function(req, res){
res.header('Access-Control-Allow-Origin'. '*');
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.status(200).send({'a':'b'});
});
When I make requests in my firefox browser, I still get the error:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.example.com/api/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."
This is how I make the request on the client side:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
console.log(this.response);
}
};
xhr.open('GET', 'http://www.example.com/api', true);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
xhr.send(null);
Dont set the "Access-Control-Allow-Origin" on client side,It should be added only on server-side.So,the server knows to accept request from all origins.
You can try cors module with express.
var express = require('express');
var cors = require('cors');
var app = express();
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
If you want for specific domain.
var express = require('express');
var cors = require('cors');
var app = express();
var allowlist = ['http://example1.com', 'http://example2.com']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (allowlist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true }; // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false }; // disable CORS for this request
}
callback(null, corsOptions); // callback expects two parameters: error and options
}
app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for an allowed domain.'});
});
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80');
});
For more detailing click here
HTH

Server in node which accepts cors from third party api, and then fetch it client side javascript

I want to create node server that allows CORS, which accepts third party api JSON, and then fetch it in client side javascript.
So my question is how to set up server?
And then how to fetch data from that server ?
Third party api is https://api.kursna-lista.info/b7b80a59415046c33449b6a2a96bd4d8/kursna_lista
My node server is created like this.
var express = require('express');
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('https://api.kursna-lista.info/b7b80a59415046c33449b6a2a96bd4d8/kursna_lista', function (req, res) {
var data = res.data;
res.json(data);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
And then later fetch that api trough server in client side JavaScript.
fetch('name of the link from node sever').then(function(res) {
return res
}).then(function(data) {
console.log(data);
}).catch(function(err) {
console.log(err);
});
Thanks in advance.
Here's a basic server in node to get started, you should install the 'request' package along with express for it to work. Request module will help make calls to the external api.
var express = require('express');
var app = express();
var request = require('request');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/api/get', function(req, res){
request({
method: 'GET',
uri: 'https://api.kursna-lista.info/b7b80a59415046c33449b6a2a96bd4d8/kursna_lista'
}, function (error, response, body){
if(!error && response.statusCode == 200){
res.json(body);
}
})
});
app.listen(3000);
Now, to request that data from your server...
fetch('/api/get').then(function(response) {
console.log(response);
}).then(function(data) {
console.log(data);
});

How to enable cors nodejs with express?

In summary I am using a viewer like api of dicom files called cornerstone, for this I connect to the WADO service of dc4chee to get the dicom, dcm4chee runs port 8080, and my application on node uses port 3000, so I am trying to show The browser's dicom.
https://www.npmjs.com/package/cornerstone-wado-image-loader
This is the error displayed by the browser
XMLHttpRequest can not load http: // localhost: 8080 / wado? RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 & contentType = application% 2Fdicom & transferSyntax = 1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is therefore not allowed access.
In the documentation specified
Note that the web server must support Cross source resource sharing or the image will fail to load. If you are unable to get CORS enabled on the web server you are loading DICOM P10 instances from, you can use a reverse proxy. Here's a simple Node.js based on http-proxy that adds CORS headers that you might find useful.
And show this example code but I'm using express and this code does not work
Var http = require ('http'),
    HttpProxy = require ('http-proxy');
Var proxy = httpProxy.createProxyServer ({target: 'http: // localhost: 8042'}) .listen (8000);
Proxy.on ('proxyRes', function (proxyReq, req, res, options) {
  // add the CORS header to the response
  Res.setHeader ('Access-Control-Allow-Origin', '*');
});
Proxy.on ('error', function (e) {
  // suppress errors
});
Also use npm cors here the code
Var express = require ('express')
Var cors = require ('cors')
Var app = express ()
 
App.get ('/ products /: id', cors (), function (req, res, next) {
  Res.json ({msg: 'This is CORS-enabled for a Single Route'))
})
 
App.listen (80, function () {
  Console.log ('CORS-enabled web server listening on port 80')
})
But with this I enable the cors on port 3000 and not the 8080, I need the mode to activate or add 'Access-Control-Allow-Origin in headers response and not in header request,
How can I do to add CORS on port 8080 where dcm4chee runs from NODEjs?
update!
The server responds with the following;
RESPONDE HEADER
Content-Type:application/dicom
Date:Sat, 01 Apr 2017 01:15:38 GMT
Expires:0
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Powered-By:Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA
date=200807181439)/JBossWeb-2.0
REQUEST HEADER
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:es-ES,es;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:localhost:8080
Origin:http: //localhost:3000
Referer:http: //localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/55.0.2883.87 Safari/537.36
HOW TO ENABLE THE CORS IN RESPONSE HEADER??
do
npm install cors --save
and just add these lines in your main file where your request is going.
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
Adding CORS(Cross-Origin-Resource-Sharing) to your node, express app is quite easy...
You need to install cors library via npm first, using the command below:
npm install cors -S
and if you need it globally, just add -g flag to it...
Then in your express app, do this:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
Also these are other examples for cors from their doc:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
Configuring CORS Asynchronously:
var express = require('express')
var cors = require('cors')
var app = express()
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
To enable cors you can do this:
var cors = require('cors');
app.use(cors());
// to change your ports for different cors stuff:
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'), function() {
console.log('we are listening on: ',
app.get('port'))
});
Remember that cors are middleware, so you will want to have app.use before it so that your incoming requests will go through cors before they hit your routes.
You can change the ports depending on which one you want to use. I am pretty sure you can also replace the || with && to listen on multiple ports and set cors on those.
In raw node, I believe you have to use the writeHead, but I am not sure about the raw node implementation.
The error displayed by the browser means, server localhost:8080 refused a request from localhost:3000, It seems cors didn't set well on server localhost:8080.
The response header should have something like this:
Access-Control-Allow-Headers:Content-Type,Content-Length, Authorization, Accept,X-Requested-With
Access-Control-Allow-Methods:PUT,POST,GET,DELETE,OPTIONS
Access-Control-Allow-Origin:*
Try add cors header in your 8080 server.
app.all('*', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//...
});
CORS didn't work on localhost until I added http:// to request url
Not working localhost:3001
Working fine http://localhost:3001
This is what my working code looks at the end
Node side
var cors = require('cors')
const app = express();
app.use(cors()); // Make sure this line comes right after express()
Front-end side
let response = await axios.post("http://localhost:3001/uploadFile", formData);
// the http:// is required cors to work for localhost
This code is helped me to resolve the resources cors issue with the express. And You can use other options easily with the asynchronous origin configuration.
var cors = require('cors'); //import cors module
var whitelist = ['http://localhost:8000', 'http://localhost:8080']; //white list consumers
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(null, false);
}
},
methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
credentials: true, //Credentials are cookies, authorization headers or TLS client certificates.
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'device-remember-token', 'Access-Control-Allow-Origin', 'Origin', 'Accept']
};
app.use(cors(corsOptions)); //adding cors middleware to the express with above configurations
To solve this problem first of all you have to understand what Access-Control-Allow-Origin: The value for this Header will be the host from where you will send a request to your server ( eg express ).
Step 1: allow cors on the server side, (to allow cross origin request you can use * instead of http://localhost:3000:
var express = require("express");
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Step 2: just use your http client , I am using Axios:
var qs = require("querystring");
var axios = require("axios");
const sendEmail = (email, subject, template) => {
var data = qs.stringify({
email: email,
subject: subject,
template: template,
});
var config = {
method: "post",
url: "https://abc-domain.com/endpoint",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: data,
};
axios(config)
.then(function(response) {
console.log(JSON.stringify(response.data));
})
.catch(function(error) {
console.log(error);
});
};
module.exports = sendEmail;
//Définition des CORS Middleware
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type, Accept,Authorization,Origin");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});`enter code here`
I also met this issue.
To solve it I used CORS module and imported it into my routings:
import cors from 'cors';
const router = new Router();
router.get('/posts', cors(), PostController.getAll);
add the following in your route handler
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
for example instead of this
app.get("/monsters", (req, res) => {
const arr = [
{
name: "Abanoub",
id: "215",
},
{
name: "Mena",
id: "sd5",
}
];
res.send(arr);
});
use headers I mentioned before.
so the route handler will be like that:
app.get("/monsters", (req, res) => {
const arr = [
{
name: "Abanoub",
id: "215",
},
{
name: "Mena",
id: "sd5",
}
];
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.send(arr);
});

Categories