Bluemix Cors disable Node.js - angularjs

I am not able to avoid this error on my browser - XMLHttpRequest cannot load https://xyz.mybluemix.net/get_user_byId.Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://a.x.y.z:9000' is therefore not allowed access. The response had HTTP status code 404.
I am using every measure required to actually allow cross origin calls, but still it gives me an error.
var app = express();
var cors = require('cors');
app.use(cors());
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.header("Access-Control-Allow-Methods", "GET, POST, PUT");
next();
});
app.get('/get_users', cors(), function(req, res) {...}
I am calling this api like - (standard $http angular way)
return $http.post(base+"get_user_byId", id)

You need only:
var cors = require('cors'); //Importing this middleware enables CORS
and
app.use(cors());
to allow CORS in express/connect applications
Delete these lines:
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.header("Access-Control-Allow-Methods", "GET, POST, PUT");
next();
});
and set your GET API with:
app.get('/get_users', function(req, res) {...}
Reference - Enable all CORS: https://www.npmjs.com/package/cors#simple-usage-enable-all-cors-requests
In angularJS you have to call that API with GET method (no post) because you have defined /get_users api with get method.
I suggest you to use this snippet:
var par = {
id: myId,
};
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method : "GET",
params: par,
url : base + "/get_users"
}).then(function mySucces(response) {
$scope.myData = response.data;
}, function myError(response) {
$scope.myData = response.statusText;
});
});

Related

CORS error occurs when HTTPS applied to the my server using Let's Encrypt

I have a Digital Ocean Linux server.
I deployed my REST API and also front end in the same server.
My Back End runs using Node.JS and front end using AngularJS.
After enabling HTTPS, I changed all the REST URLs into HTTPS.
Like this :
var mainHost = "https://xxx.xxx.xxx.xx:7000/api";
Now I'm getting this CORS error :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxx.xxx.xxx.xx:7000/api/user_manage/login. (Reason: CORS request did not succeed).
I am using Node.JS CORS plugin also.
var cors = require('cors');
var app = express();
app.use(cors());
This started when I added HTTPS and I tried many things. Including changing the .htaccess and adding some meta tags. Still no good. What is the reason for this ? Why CORS error comes after adding HTTPS ? Please help me to solve this.
This is the controller call for the service layer :
sessionService.getAllSessions(100, 0).then(function (data) {
console.log(data);
$scope.allSessions = data.data;
});
And this is the service layer :
getAllSessions: function (limit, offset) {
return $http({
method: "GET",
url: host.session_manage + '/session/' + limit + '/' + offset
}).then(function (response) {
return response.data;
});
}
I'm not using headers in the service call as you can see in the above section.
This is the server code snippet :
var express = require("express");
var bodyParser = require("body-parser");
var morgan = require("morgan");
var config = require("./config");
// var cors = require('cors');
var app = express();
// app.use(cors());
// app.use(cors({
// origin: 'https://xxxxxx.com'
// }));
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.set('views', './app/views');
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan('dev'));
var session = require('./app/routes/session')(app, express);
app.use('/api/session_manage', session);
app.listen(config.port, function (err) {
if (err) {
console.log(err);
} else {
console.log("localhost:7000");
}
});
Thank you guys.
You are in production you don't want to allow CORS access for all origins but if you need to allow cross origin requests from some specified host(s) you can do add the following code:
server.use(cors({
origin: 'https://example.com'
}));
This will allow https://example.com to send cross origin requests to your Express server without the Same Origin Policy getting in the way.
You can also enable CORS for a single Express route
server.get('/endpoint', cors(), function (req, res, next) {
res.json({msg: 'This has CORS-enabled for only this route: /endpoint'})
})
If you want to allow multiple origins you need to use a function (for origin instead of a string) that dynamically set the CORS header depending on the origin making the request and a white list that you specify which contains the origin to allow.
var whitelist = ['http://example.com', 'http://othersite.com'];
var options = { origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
server.use(cors(options))

No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've seen several questions and answers around this and mine is half working.
I have a node.js api server with url api.domain.com and the website on an nginx server at www.domain.com when I do the following in angular the request goes through on the api server, I see the request I see it getting parsed and put into the database. However, on the client side I do not get a return right away and then eventually I will see No 'Access-Control-Allow-Origin' header is present on the requested resource.
I know what is causing this behavior but shouldn't it throw the error before it hits the API server? Also note that the node.js server has cors enabled. The response that should be coming back is json.
$http({
method: 'POST',
url: "http://api.domain.com/addtrans/" + $scope.accountID,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
payload: JSON.stringify(trans)
}
}).success(function (result) {
$scope.trans = {};
console.log(result);
});
I have used the below middleware for all of our projects and it has been proven to work best.
const allowCors = (req, res, next) => {
/** Allow all origins, for now TODO */
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Authorization, Content-Type');
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
/** Browser check for pre-flight request to determine whether the server is webdav compatible */
if ('OPTIONS' == req.method) {
res.sendStatus(204);
}
else next();
};
// Put this code before the routes you want to allow CORS to
app.use(allowCors);
You should change the Allow-Origin to something more restricted for security reasons.
The above code covers CORS as well as pre-flight on most browsers(this ia major issue we were having in the beginning).
i used this a while ago (express 3.x):
// npm install --save cors
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(express.static());
app.get('*', function(){});
require('http').createServer(app).listen(3000)
Remember that the cors header should be on the response which is coming from server not the request which is sent from client.
You can use a middleware to enable cors on the server:
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
//...
app.configure(function() {
...
app.use(allowCrossDomain);
...
});

Cross orgin error in google chrome for the api call

in the nodejs backend i have added this code to the server.js
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();
});
but in angularjs 2 client side in google chrome is throwing this error
XMLHttpRequest cannot load http://localhost:8080/team. 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. The response had HTTP status code 405.
this is the service code for angular2 i'm using
export class DataService {
// URL to web api
constructor(private http: Http, private _configuration: Configuration,private team:Team) {
//this.actionUrl = _configuration.ServerWithApiUrl;
this.actionUrl = "http://localhost:8080/team";
}
private actionUrl: string;
addData(postData: Team): Observable<Team[]> {
//let body = JSON.stringify({ Team });
this.team = postData;
console.log(this.team);
let body = JSON.stringify({ postData });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(this.actionUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
UPDATED:
For your new error message: Angular2 is lower-casing the headers.
Please update your backend to accept content-type too.
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, content-type, Accept");
You cant test post's to this URL: http://posttestserver.com/post.php?dir=anyNameYouWillFind
And can see your posts there: http://posttestserver.com/data/
Browse to year, month, day and anyNameYouWillFind ..
OLD:
you have to prefix your url!!
this.http.get('http://localhost:8080/v1_user/45646/team');
Fixed it by adding this to the backend node.js
// access control --> allowed all origin
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");
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
})
.options('*', function(req, res, next){
res.end();
})
;

Handle sessions using Express-Sessions

Im new working with nodeJS. I have a webpage (with AngularJS) in a AWS ec2-server that gets information from a nodeJS(Express) server. Im trying to keep logged my users once they log in, even if they refresh. I have read that I can do that using express-sessions. This is my code in the client side:
$http({
method: 'GET',
url: 'http://ec2-bla-bla-bla.compute.amazonaws.com:8080/verifySession'
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
});
//And here i have the http post method that call login webservice
This is my server code:
var express = require('express');
var bodyParser = require('body-parser');
var path = require("path");
var session = require('express-session');
var app = express();
var loginManual = require('./model/ws_package/loginManual.js');
var sess;
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.use(session({secret: 'ssshhhhh'}));
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.static(path.join(__dirname + '/view')));
app.get('/verify',function(req,res){
sess=req.session;
if(sess.email){
res.send({state:1,email: sess.email});
}
else{
res.send({state:-1,email: "NE"});
}
});
app.post("/login",function(req, res)
{
var userEmail; //here is myuseremail
//I have some login code here and if it is successful:
sess = req.session;
sess.email=userEmail;
res.send(response);
}
);
It is not working, but when I tested /login and /verify webservices, directly in my browser, writing the url, it works. Another thing I discovered is that everytime I make a new $http method from angular, my session id changes, so I dont know if that could mean something that affects me. How can I solve this? Sorry for my english, i am Costa Rican! Thanks!

Enabling CORS on express-4

I have the following code in Angular.JS
$scope.resolve = function(){
alert('In here');
$http.get('http://cdsws.u-strasbg.fr/axis/services/Sesame?method=sesame&resultType=x&name=m3')
.success(function(data,status,headers,config){
alert("data"+data);
})
.error(function(data,status,headers,config){
alert("Error in Web service!"+status);
});
};
I have added the required headers in express but still not able to call the web service
var app = express();
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin','*');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
res.header('Access-Control-Expose-Headers', 'Content-Length');
res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range');
if (req.method === 'OPTIONS') {
return res.send(200);
} else {
return next();
}
});
What else needs to be done to enable CORS?
I even tried using the cors middleware in node Jsbut no success!
var cors= require('cors');
var corsOptions = {
origin: 'http://localhost:3001/'
};
app.use(cors(corsOptions));
is there any way by which we can access the other domain URL , I can not add Access-Control-Allow-Headers to the other domain, the change needs to be done on the client side.

Resources