Unable to redirect to fitbit OAuth2 endpoint - node.js

I am trying to get authorize from Fitbit. when I use Oauth2.0
frontend angular4
getAuthFromFitbit() {
this.http.get(this.BASE_URL + "/fitbit").subscribe(res => {
console.log(res.json());
});}
backend node.js
then I got this problem:

The error you see in the browser console is coming from a fitbit request, not from your server. Setting headers on your server will not help much in your case.

This is a Cross Origin Resource Sharing issue. You need to disable CORS in your browser.

i use this when front and back is not in same server.
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
})
Could you try this.

Related

Access to XMLHttpRequest problems with Cors

I took an Ionic 5 course and when I did one of the exercises I wanted to put the backend written in JS inside github and heroku, when starting my authentication within my application it throws me the following error:
error
my backend is en node and express:
//allow cross config
server.app.use( cors({ origin: true, credentials: true }) );
server.app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'x-token, content-type');
next();
});
my app need to login and return one token per user, and this token is use in headers in other petitions
To avoid CORS issues i think you should use native http requests in your ionic app.
That is the simpliest way to solve your issue in my point of view.

Getting 'has been blocked by CORS policy' while trying to upload file

I was trying to set a ui for uploading excel file using angular8. The front and backend (nodejs) applications are running in two different ports. While clicking upload button i am getting errors.
Have tried adding this code:
app.use(cors());
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
still same error
typescript:
url_='http://localhost:3000/product/upload-exel'
public uploader :FileUploader = new FileUploader({
url:this.url_
});
html:
<input type="file" id="file"
ng2FileSelect [uploader]="uploader"
[(ngModel)]="path">
OPTIONS http://localhost:3000/product/upload-exel 404 (Not Found)
Access to XMLHttpRequest at 'http://localhost:3000/product/upload-exel' from origin 'http://localhost:4000' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
My code is deployed on AWS and this thing worked for me:
Besides all the technical things (to be added) which are stated on several other Q/A make sure that your function returns the response to the front-end within 29 seconds. This is the default timeout (and maximum timeout) set for your response. After fixing this I was able to break the CORS error.
The error message indicates that 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'.
If your backend server is http://localhost:3000/ and your client frontend is running on http://localhost:4000/, then your backend headers should be:
Backend Server
app.use(cors());
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4000/');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST,
OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
In your backend, Since you are using cors module, you can do this and it is safe
var cors = require('cors')
var app = express()
//set options for cors
//add your frontend addresson in the origin
//for testing add localhost and port
var corsOptions = {
origin: 'http://localhost:3000',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
//for specific endpoint enable cors
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for only example.com.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})```
This may happen also when using nginx on Mac (homebrew)
If you enable debug error loging you can see this error when uploading - this is what's actually causing the CORS error:
25 open() "/usr/local/var/run/nginx/client_body_temp/0000000001" failed (13: Permission denied)
That may be a bug in the homebrew nginx: https://github.com/denji/homebrew-nginx/issues/124
Not sure if this is the proper fix, but I was able to get it to work this way:
sudo chown YOUR-MACOS-USER /usr/local/var/run/nginx/client_body_temp/
After that restart nginx

Allowing Multiple Cors In Node Express

I'm trying to allow multiple cors with node in my express api, I've been able to get it to work but am currently facing two issues.
I can't connect to my api using postman because I checked and it turns out the origin sent from postman is undefined.
I have a mobile app which also communicate with the server, the issue is after I allowed multiple specific origin, the app also can't communicate with the server.
How do I solve this issue, because I can't leave my api server open to allow communication from every origin.
Have you tried with Cors for nodejs
Add the dependency:
$ npm install cors --save
And then add cors to your app.js
var cors = require('cors')
var app = express()
app.use(cors())
On production try this instead of * on Access-Control-Allow-Origin header, For development allow any source will not be a problem (depend on your scenario)
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "yourdomain.com");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Expose-Headers','Content-Type,expire');
next();
});
Try this one in your server. If you want to pass extra header parameter you need to add those variable in res.setHeader('Access-Control-Allow-Headers', 'Content-Type , token'); but remember don't user '-' in the variable name.

Disable CORS in Expres.io for socket.io calls

I try to connect from angular to a Express.io socket, but I have error 404 CORS. How can I solve this?
XMLHttpRequest cannot load http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1447367208172-29. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
If I load this route directly from browser directly, it works well But from localhost:80 angular to localhot:3000 express.io not works.
In my express.io I disabled the CORS, and it works well for the normal ajax requests, but not for socket.io :
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});
My initialization of socket.io in express.io:
app.http().io()
Are you running this angular app in chrome? I imagine its the same way for most browsers but on chrome CORS will not work with localhost: https://code.google.com/p/chromium/issues/detail?id=67743
What I've done to get around this in the past is alter my hosts (if on Windows). You can also use lvh.me instead of localhost if you do not want to alter your hosts file on Windows.

ExpressJS, AngularJS - Cross domain request issue

I'm developing a back-end RESTfull app with ExpressJS(Node). And reading with angularJS. I got this error on chrome.
**
XMLHttpRequest cannot load http://local.dev:3000/api. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://local.dev:63359' is therefore not allowed
access.
**
Note : ExpressJS api working on Postman app. Postman app is successfully get data.
This is my code
ANGULARJS
$http.post("http://local.dev:3000/api",{
"username" :'JJ',
"email" : 'email#email.com'
}).then(function(mes){
console.log(mes);
});
EXPRESSJS
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
Thanks in advance.
This is the CORS browser limitation. Your server will have to response with some headers to tell the browser cross domain access is allowed.
If you search around there are a few middleware as node package (eg. express-cors) available. But I found sometimes they does not work as what I want. So here is the one I used:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Cache-Control");
if (req.method === 'OPTIONS') {
res.statusCode = 204;
return res.end();
} else {
return next();
}
});
By the way, you will have to use this middleware for the server you are accessing ( http://local.dev:3000/api )
When trying to access a cross origin resource, the browser will try to make a Options request to read these special header and decide if the server allow the access. This is why, for Options request, you can response straight away without passing the flow using 'next()'.
You can also edit the list of methods allow by editing the Access-Control-Allow-Methods header.
Access-Control-Allow-Headers header is optional, you can use it to limit the headers that can be used.

Resources