We deployed our nodejs app to aws ,but it is giving this error while accessing any api,
Access to XMLHttpRequest at 'https://vkluy41ib9.execute-api.ap-south-1.amazonaws.com/dev/api/auth/login' from origin 'https://cmc-app.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Now the issue if our node app is hosted on localhost its working fine but deploying on live server its throwing error
this is our code :
app.options(cors());
app.use(function (req, res, next) {
//Enabling CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization"
);
next();
})
If you want to use cors() then you need to write:
app.options("*", cors());
otherwise it will not be registered correctly. Using this method, the handler returned from cors() will be used on all OPTIONS-requests.
The second part where you do app.use is not necessary, because it does nearly the same as the method before.
To get the result you wanted with the second part, you could write:
app.options("*", cors({
methods: ["GET", "HEAD", "OPTIONS", "POST", "PUT"],
allowedHeaders: ["origin", "X-Requested-With", "Content-Type", "Accept", "x-client-key", "x-client-token", "x-client-secret", "Authorization"]
}));
All configuration options for cors are listed here: https://www.npmjs.com/package/cors#configuration-options
Related
I have been trapped in very weird problem.
i have CORS configured on Nodejs backend using CORS package
const whitelist = ['https://www.domainname.co/', 'https://admin.domainname.co/','https://organizers.domainname.co/'];
if(process.env.env)
var corsOption = {
origin: whitelist.indexOf(req.header('Origin')) !== -1,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true,
allowedHeaders: [
"Access-Control-Allow-Headers",
"Access-Control-Allow-Origin",
"x-www-form-urlencoded",
"Origin",
"X-Requested-With",
"Content-Type",
"Accept",
"Authorization",
],
exposedHeaders: [
"Access-Control-Allow-Headers",
"Access-Control-Allow-Origin",
"x-www-form-urlencoded",
"Origin",
"X-Requested-With",
"Content-Type",
"Accept",
"Authorization",
],
};
app.use(cors(corsOption));
i have three frontend apps connected to same backend.
working on their respective subdomains
issue i am facing is everything is working fine but there is one specific API which is is throwing following error
Access to XMLHttpRequest at 'https://api.domainname.co/api/admin/event/add' from origin 'https://admin.domainname.co' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
strangely enough this works alright on my machine but my client has 2 different machines and it is not working on both of them.
and i am at loss from where to start debugging it.
I tried following things on client's machine via remote control.
use website in incognito on chrome.
use firefox.
use microsoft edge.
but everything ends in same result.
const whitelist = ['https://www.domainname.co/', 'https://admin.domainname.co/','https://organizers.domainname.co/'];
app.use(
cors((req, callback) => {
const corsOption = {
methods: "GET, POST, DELETE, PUT, PATCH, HEAD, POST, OPTIONS",
allowedHeaders: "Access-Control-Allow-Origin, x-www-form-urlencoded, Origin, X-Requested-With, Authorization, Content-Type, Accept",
exposedHeaders: "Access-Control-Allow-Origin, x-www-form-urlencoded, Origin, X-Requested-With, Authorization, Content-Type, Accept",
credentials: true
};
if (!req.get("Origin")) {
callback(null, { ...corsOption, origin: whitelist });
return;
}
if (allowedOrigins.indexOf(req.get("Origin")) !== -1) {
corsOption.origin = true;
callback(null, corsOption);
} else {
corsOption.origin = false;
callback(new Error("You are not allowed to access this resource"), corsOption);
}
})
);
You can pass a function to cors to configure when it is used by the app. This function will receive the request and a callback as arguments. You can set the origin value of the options object by checking if the domain exists in the whitelist. You can also ignore requests that don't have an Origin header set. Finally, you need to add OPTIONS to the list of allowed methods to enable pre-flight for HTTP requests that are not GET/HEAD/POST or have custom headers.
I tried everything in comments and answer nothing worked because it wasn't a problem with nodejs or cors package instead it was problem with NGINX, nginx had default request size limit this particular request was exceeding that size. so to solve this i had to increase limit in
nginx.conf
client_max_body_size 100M;
and my problem got solved.
Thank you people for your valuable time for devising solutions.
I have a web app with a Node.js backend and Angular front end, both on the same server (Windows Server 2016), however, using different domains. So the front-end is at http://frontend.mydomain.com and the backend is at http://backend.mydomain.com.
Unfortunately I didn't write this web app, nor do I have any experience with Node.js or Angular.
The web app was working perfectly on the older server. However, we have moved both the front-end and the back-end to a new web server, and now, when trying to load it, I get this error message:
/#/login:1 Access to XMLHttpRequest at 'http://backend.mydomain/authenticate' from origin 'http://frontend.mydomain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Now I'm looking at the server.js file in the backend folder, and this is what it looks like:
var express = require('express');
const sql = require("mssql");
// var cors = require("cors");
var app = express();
var port = process.env.PORT || 3000;
// app.use(cors());
var config =
{
server: "**************",
database: "**************",
user: "**************",
password: "**************",
port: 1433,
connectionTimeout: 1500,
requestTimeout: 1500
};
app.use(function(req, res, next)
{
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk)
{
data += chunk;
});
req.on('end', function()
{
req.body = data;
next();
});
});
var cors = require("cors"); and app.use(cors()); where commented out, so I tried uncommenting it (and restarting the web service in IIS) but it made no difference.
I did some research, and tried adding things such as
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();
}
as well as a myriad of other things, always remembering to restart the web service in IIS after each change, but nothing I do seems to make a difference. Any suggestions anyone please? Thanks...
EDIT:
So the welcome/login page loads. But as soon as I type in my username and password, and hit the Submit button, I get the error described above. Looking at Developer Tools -> Network, I see that "authenticate" is in red, and when I click on it, it shows this:
Request URL: http://backend.mydomain.com/authenticate
Referrer Policy: no-referrer-when-downgrade
Content-Length: 1208
Content-Type: text/html
Date: Mon, 30 Mar 2020 10:53:26 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,es-AR;q=0.8,es;q=0.7
Connection: keep-alive
Content-Length: 34
content-type: text/plain
Host: backend.mydomain.com
Origin: http://frontend.mydomain.com
Referer: http://frontend.mydomain.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
myusername!##$%&mypassword
p.s. i have changed actual domain names, usernames and passwords...
It may happen sometimes when the origin didn't implemented correctly, you can setup the back-end for this situation:
Use cors npm (in nodejs back-end) for setup the allowed origin by yourself:
const cors = require("cors");
app.use(cors({
origin: //Hardcoded string of your coming request path or regex for filter anything,
//Like this: "http://frontend.mydomain.com" or /frontend.mydomain.com/
credentials: true //Allow the server to get cookies and other auth data from other
// domains and ports to send cookies
}));
This is worked for me but in some cases you may get in trouble with preflight requests which are some kind of issue that the origin (a path which request is coming from) is not implemented correctly, You have to set a Express middleware for set some header manually (Like yourself):
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://frontend.mydomain.com");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
next();
});
You have to put this all together like this:
const cors = require("cors");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://frontend.mydomain.com");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
next();
});
app.use(cors({
origin: //Hardcoded string of your coming request path or regex for check in string,
//Like this: "http://frontend.mydomain.com" or /frontend.mydomain.com/
credentials: true //Allow the server to get cookies and other auth data from other
// domains and ports
}));
In res.header("Access-Control-Allow-Origin", "http://frontend.mydomain.com") it's better that you put a specific domain for the origin instead of a "*" because it may be not secure at all. When you put "*" CORS policy would prevent the credentials to be passed.
Hope this works.
I would check in your browser (use the developer tools, go to Network) and ensure you're seeing requests successfully returning allowed methods, headers etc.
You should see headers like:
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: *
If these headers are not being send back, something is going wrong with the CORS setup.
You should at the very least receive an Access-Control-Allow-Origin header.
It may be that something is swallowing the headers you are sending back (such as a proxy). In this case the calls will fail.
Try adding the allowed http methods in your app.use()-
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", "Origin, X-Requested-With, Content-Type, Accept")
next();
}
When sending a request over CORS from my React app to my Node.JS and Express.js backend i get an:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/students/login. (Reason: CORS preflight channel did not succeed).
Im using axios for sending out requests and this is the request configuration:
({ email, password }) => {
return axios.post(API_ENDPOINT + UCENIK.post.login,
{ email, password },
{
withCredentials: true,
Headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
}
I have tried allowing CORS in Express with these headers:
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-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
next();
});
Edit: fixed using npm Cors module and providing this object for settings:
{
origin: 'http://localhost:3000',
cors: true
}
I assume this is only a development problem, because your express instance and reactjs frontend server run on a different port. In the production environment this probably isn't the case.
In stead of using CORS in your development cycle try to proxy the request from your frontend server to your express server.
For exmple the webpack devserver has a seperate proxy configuration https://webpack.js.org/configuration/dev-server/#devserver-proxy
I have a project that sends HTTP requests from the client using Axios
axios.create({
baseURL: `http://localhost:8081/`,
withCredentials: true
})
And I suppose this allows cookies -Which I am sure it shows in the browser before you ask- to be sent with the requests.
The problem occurs in the back-end, when this error shows in the log:
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:8080' is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
I tried this:
app.use(cors({
//origin : to be set later
credentials: true,
}))
and this instead:
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-Credentials", true);
next();
});
but neither seems to work.
EDIT - Here is the answer for future visitors
With the help of the participants in comments, I found out I had to set the origin value:
app.use(cors({
origin : "http://localhost:8080",
credentials: true,
}))
I know it's too late for OP, but for those who keep comming here - what helped me is:
app.use(cors({
preflightContinue: true,
credentials: true,
}));
source: https://expressjs.com/en/resources/middleware/cors.html
I got this problem and I fixed it by setting the header "Access-Control-Allow-Origin" to the URL of my frontend instead of "*"
More details: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 4 years ago.
I am working on angular 5 application. my site is working in chrome browser well. when i try to log in mozila firefox. i am getting the following CORS exception. please help me with it.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://00.000.000.00/login (this is server url). (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
code:
const header = {
headers: new HttpHeaders({
'content-Type': 'application/json',
'accept':'application/json'
}),
'responseType': 'text' as 'text',
}
it is working chrome browser. but it is not working in firefox browser. can you tell me the reason?
Instead of using *, use the exact headers you want. Example:
Origin, X-Requested-With, Content-Type, Accept, Authorization
If you're working with Express, or a derivative, here's an example configuration for a middleware return value:
return (req, res, next) => {
res.header('Access-Control-Allow-Origin', 'your-domain');
res.header('Access-Control-Allow-Methods', 'DELETE, GET, POST, PUT, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Credentials', true);
next();
};