Access to XMLHttpRequest problems with Cors - node.js

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.

Related

CORS was working fine but suddenly stopped working?

This is what I have in Node:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200/');
// 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-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
My front-end is in Angular. Everything was working just fine, but all of a sudden I started getting CORS errors. When I check the console, I get this:
The Initiator Context and the Allowed Origin are exactly the same. And, as I mentioned before, I was having 0 issues until all of a sudden it decided to stop working. So I don't understand what's going on here. Any help will be appreciated.
You can try with http://localhost:4200, without the last '/'

How to solve the issue response to preflight request doesnt pass access control check error?

I have a angular code in a VM, node code in another VM. I need to make an API call from this angular VM to node VM. I have included the cors module also. But still while making an API call, getting an error like
"access to xmlhttprequest at 'http:IP1' from origin 'http:IP2' has been blocked by CORS policy: Response to preflight request doesnt pass access control check: No 'Access control".
I have set header like this also,
app.use(function(req,res,next) {
res.setHeader('Access-Control-Allow-Origin','*');
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();
});
app.use(cors());
But still I'm facing an error. Can anybody tell me how to solve this error?
Try to set explicitly your localhost and add desired types of methods:
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
// desired types of methods
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
UPDATE:
For example, your node server is hosted at http://127.0.0.1:8000. Then your Angular Application should be http://127.0.0.1:4200.
UPDATE 1:
npm install --save cors
and then:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());

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

Failed to load 'endpoint': Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response

I have created one API service using nodejs and it is working fine when I accessing through the browser. But when I'm try to call it from web application (MEAN app), getting the "Failed to load http://localhost:2020/api/posts: Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response" issue.
Following code is added in index.js of the API service.
// Add headers
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-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
and added following lines in controller of the web app,
app.config(["$routeProvider", "$httpProvider", function ($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = '*';
}
]);
But no luck for added the above lines. How to resolve this issue ?
Thanks.
You need to add If-Modified-Since to Access-Control-Allow-Headers in your server code:
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,If-Modified-Since');
Also the part where you touch HTTP header on client seems useless to me, I don't think you can do anything with that.

Angular on localhost gets 404 when consuming GET api from different localhost PORT - CORS issue?

Ever since I switched to the database URL from the in-memory-web-api URL, the Angular app's JavaScript console gives me a 404 error
JavaScript console output 404 error
I've got my angular app running on lite-server using localhost:3035/
I've got a mongodb/nodejs/express database running on localhost:3039/
My angular app was "GET"-ing just fine using the in-memory-web-api url 'api/loggerData'
Any thoughts? Is it CORS? Something else? Do I need to configure the lite-server on the angular side as well?
Here's my angular Code:
private loggerUrl = 'localhost:3039/read/getall/';
getLoggerData(): Promise <Dataset[]> {
return this.http.get(this.loggerUrl)
.toPromise()
.then(response => response.json().data as Dataset[])
.catch(this.handleError);
}
Also, I've tried implementing some CORS solutions on the database side that haven't affected anything -
here's some of the database code I modified:
var app = express();
app.use(function (req, res, next) {
//Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3035');
// 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-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
No collection errors usually means, that you have left hanging some the equivalent of:
InMemoryWebApiModule.forRoot(InMemoryDataService)
in your ngModule, which interferes when you try and make "real" http-requests. So remove that from your ngModule and you should be good to go! :)
After this you might still run into problems with CORS, but this should fix the current error you get :)
And as mentioned by echonax, you should use the complete url, with http included:
private loggerUrl = 'http://localhost:3039/read/getall/'

Resources