Express CORS Works On Others Endpoints But One - node.js

I have a simple Express project as my API endpoint using cors as middleware.
The cors works on any others endpoint but one. Here is my code snapshot:
const express = require('express');
var cors = require('cors');
const app = express();
app.use(cors());
app.get('/shuttles',
tokenPassport.authenticate('bearer', { session: false }),
(req, res) => {
// ....
// implementation goes here...
// ....
})
app.get('/deposit',
tokenPassport.authenticate('bearer', { session: false }),
(req, res) => {
// ....
// implementation goes here...
// ....
})
The CORS in /deposit is working but not with /shuttles.
NB: Nevermind the tokenPassport require. It is for authorization.
EDIT
Here is the snapshot of network tab in chrome devtool. It's only send OPTIONS request and that is the response header. No Access-Control-Allow-Origin header in the response.

you can create your own middleware, in your app.js or server.js file.
//CORS
app.use((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,Accept,Authorization');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
if you want to use the cros module
const corsOptions = {
"origin": "*",
"methods": "GET, HEAD, PUT, PATCH, POST, DELETE",
// other options
}
app.use(cors(corsOptions));

Hi can you try adding this line in the express server
app.options('*', cors()); . also can you check whether from the client application when you are invoking the /shuttles end point are you adding 'access-control-origins' header to *

After some meditation finding the solution in the universe, my Express application is hosted in Google App Engine and I realized that my dispatch.yaml contains
- url: "*/shuttles*"
service: shuttle
It is the source of the problem.
Just rework the shuttle service and the routing then it solved :D
Thanks for all your comment, they all right.

Related

CORS Issue: Unable to send post request using NodeJs and Angular

I am getting this message when trying to send a post request:
Access to XMLHttpRequest at 'http://localhost:3002/api/products/checkout' from origin
'http://localhost:4200' has been blocked by CORS policy: Request header field content-type
is not allowed by Access-Control-Allow-Headers in preflight response.
Right now I'm simply trying to send data to my backend and then log it in the console. Get requests work fine but for some reason I get that CORS error when trying post. Here is my code:
Angular code:
//api call
return this.http.post('http://localhost:3000/api/checkout', cart)
NodeJs code:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Header',
'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, DELETE, OPTIONS');
next();
})
app.post("/api/checkout", (req, res, next) => {
const cart = req.body;
console.log(cart)
res.status(201).json()
})
module.exports = app;
In the network calls I can see that Request Headers is:
Access-Control-Request-Headers: content-type
while Response Headers is:
Access-Control-Request-Headers: Origin, X-Requested-With, Content-Type, Accept
I'm not sure if content-type being lower case has anything to do with the issue.
You should use req.set instead, just change setHeader to set only. Here is the document https://expressjs.com/en/api.html#res.set
And if you just using localhost, there's another easier option, you can use proxy. More information can be found here https://angular.io/guide/build#proxying-to-a-backend-server
I think the problem that you wrote Access-Control-Allow-Header instead of Access-Control-Allow-Headers, but I cannot test it now.
Be aware that you need to serve OPTIONS requests too. Which is just responding with an empty message body using the same headers. You can get these kind of OPTIONS requests before PUT, PATCH, DELETE from certain HTTP clients e.g. from browsers too.

Unxpect CORS policy error when using auth api from locally

First of all, i have an backend RESTapi running on my ubuntu server on the cloud(works perfectly 100%).
And I also have an frontend webapplication running on the same server(works perferctly aswell), and i can use the login system and all that stuff.
Now my issue: I am deploying the frontend locally at my computer for development purposes, but i still want to have the connection to my backend at the cloud instead of also deploying the backend locally.
Problem is now that when im using the authentication from my local computer i get this error:
Access to fetch at 'http://ip-adress-to-the-backend-at-the-cloud:5000/api/auth' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://*:3000' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The thing is: it worked perfectly logging in while using the webapp locally at my computer until last week.. Now that i made some changes in my ".env" file, "server.js" and "routes.js" file, it doesnt work.
The strange thing is that i tried removing the changes from those files but still aint working.
Here is my .env file:
APP_PORT=*****
DB_HOST=*****
DB_USER=*****
DB_PASSWORD=******
DB_NAME=******
JWT_SECRET=******
JWT_KEYSECRET=*******
ALLOWED_ORIGIN=http://ipadress_to_both_the_frontend_and_backend:3000
here is my server.js:
const express = require('express');
const app = express();
require('dotenv').config();
if(process.env.JWT_SECRET == undefined || process.env.JWT_KEYSECRET == undefined){
console.log("Fatal error: Secret is not set")
process.exit(1);
}
require('./startup/routes')(app)
require('./startup/database')
app.listen(process.env.APP_PORT, () => {
console.log("Server is running: " + process.env.APP_PORT);
})
and my routes.js:
require('dotenv').config();
const users = require('../api/user/user.router')
const keys = require('../api/keys/keys.router')
const equipmentType = require('../api/equipmenttypes/equipmenttype.router');
const auth = require('../api/authentication/auth.router')
const helmet = require('helmet')
const express = require('express')
module.exports = function (app) {
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'))
app.use(helmet.xssFilter())
app.use(helmet.frameguard())
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGIN);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, x-auth-token, x-api-key');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
})
app.use('/api/user', users)
app.use('/api/auth', auth)
app.use('/api/key', keys)
app.use('/api/equipmenttypes', equipmentType)
}
Firstly, install cors by npm i cors
Add this to your server.js file:
const cors = require("cors");
app.use(cors());
The solution was simple, I changed the line inse my env file this:
ALLOWED_ORIGIN=*
No, this is not a good thing to do, and not secure at all, but now i can accsess the backend api from localhost, and i can optimize my work.

CORS Header Issue between react / express

I'm having a problem with CORS, despite reading and implementing various solutions on SO.
I have an app that uses Express/NodeJS as an api and React JS as a front end.
In development, the react app http://localhost:3000 is able to talk to the express backend http://localhost:9000with app.use(cors()).
Now I'm trying to use this app in production.
Both apps are kept in separate git repositories.
React is deployed as a static website on aws s3 and works fine.
Node JS is deployed on Elastic Bean Stalk and is in the ready state.
I have a Postgres SQL database attached to the ebs instance(node app) that I'm able to connect to in pgadmin4.
Both apps are using the same base domain in route 53 myproject.com.
Both are configured to listen for https/443. I can hit both URLS https://myproject.com and https://api.myproject.com & they look like how they do in my localhost environment.
When I try to signup a user on my site I run into this error:
Access to XMLHttpRequest at 'https://api.myproject.com/users/signup/' from origin 'https://myproject.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Both apps are able to "see" each other but that's about where it ends.
Looking at my code, I can't figure out where the issue is taking place:
server.js
const express = require('express');
const cors = require('cors');
const logger = require('morgan');
const bodyParser = require('body-parser');
require('dotenv').config();
const PORT = process.env.PORT || 9000; // DEV
const app = express();
const corsOptions = {
origin: 'https://myproject.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
const allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'https://myproject.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.use(cors());
const { userRouter } = require('./routes/userRouter');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(allowCrossDomain);
app.use((e, req, res, next) => {
res.header("Access-Control-Allow-Origin", "https://myproject.com");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if (e) {
console.log(e);
res.status(500).send(e.message);
}
next();
});
app.use('/users', userRouter);
app.listen(PORT, () => {
console.log(`Express server is listening on PORT ${PORT}.`);
});// - TESTING
What I've tried:
Most of these solutions came from this SO post: Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
Using just app.use(cors());
Using a wildcard * instead of a domain name.
White listing my domain with cors (from this blog post): https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/
// Set up a whitelist and check against it:
var whitelist = ['https://myproject.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
// Then pass them to cors:
app.use(cors(corsOptions));
I've also moved app.use(cors()) above my routes as suggested in another StackOverflow post.
At this point, I'm stuck so any help is appreciated so thanks in advance.
Try requiring cors this way:
const cors = require('cors')({
origin: 'https://yourdomain.com',
});
This way you can add origin and then just call app.use(cors()) at the top of the express app
const app = Express();
app.use(BodyParser.json());
app.use(cors);
this is the way I usually get things to work. Another factor you may be dealing with is if the domain hasn't fully propagated yet, this may be causing your regions for aws to not recognize the domain's dns. That's just a theory though.

No 'Access-Control-Allow-Origin' header is present on the requested resource in angular app

I've angular cli project that hosted in azure and I'm making API call to different domain (in Zoho creator) so I have CROS issue I tried some solutions with no luck.
The error is
"Access to XMLHttpRequest at "https://xxxxxxx" from origin "https://yyyyyy" has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
I use expressJS as my backend and I tried to add headers but it seems not working I don't know what I'm missing
APP.JS
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
// parse application/x-www-form-urlencoded
var cors = require('cors');
// Use this after the variable declaration
app.use(cors({origin: '*'}));
// parse application/json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5000');
// 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();
});
//Set Port
const port = process.env.PORT || '5000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
I don't recognize exactly what It's happening but there's something that it makes me noise.
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5000');
This code indicate that you can only receive requests from http://localhost:5000. Are you trying to consume it from http://localhost:5000? I don't think so because the port 5000 is being used by node.js. if you want to use it, you must set Access-Control-Allow-Origin to the Server or Site where you're trying consume it from.
Example, I have a application in Angular in my machine using the port 4200, so the request header should be:
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
Or, you can use * to allow everything but It's not secure.
res.setHeader('Access-Control-Allow-Origin', '*');

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

i've created a small API using Node/Express and trying to pull data using Angularjs but as my html page is running under apache on localhost:8888 and node API is listen on port 3000, i am getting the No 'Access-Control-Allow-Origin'. I tried using node-http-proxy and Vhosts Apache but not having much succes, please see full error and code below.
XMLHttpRequest cannot load localhost:3000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8888' is therefore not allowed access."
// Api Using Node/Express
var express = require('express');
var app = express();
var contractors = [
{
"id": "1",
"name": "Joe Blogg",
"Weeks": 3,
"Photo": "1.png"
}
];
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.json(contractors);
});
app.listen(process.env.PORT || 3000);
console.log('Server is running on Port 3000')
Angular code
angular.module('contractorsApp', [])
.controller('ContractorsCtrl', function($scope, $http,$routeParams) {
$http.get('localhost:3000').then(function(response) {
var data = response.data;
$scope.contractors = data;
})
HTML
<body ng-app="contractorsApp">
<div ng-controller="ContractorsCtrl">
<ul>
<li ng-repeat="person in contractors">{{person.name}}</li>
</ul>
</div>
</body>
Try adding the following middleware to your NodeJS/Express app (I have added some comments for your convenience):
// Add headers before the routes are defined
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// 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();
});
(You might need to use 127.0.0.1 instead of localhost.)
Accepted answer is fine, in case you prefer something shorter, you may use a plugin called cors available for Express.js.
It's simple to use, for this particular case:
var cors = require('cors');
// use it before all route definitions
app.use(cors({origin: 'http://localhost:8888'}));
(You might need to use 127.0.0.1 instead of localhost.)
The request origin needs to match the allowed origin(s), and you can also have multiple of them:
app.use(
cors({origin: ['http://localhost:8888', 'http://127.0.0.1:8888']})
);
Another way, is simply add the headers to your route:
router.get('/', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
res.setHeader('Access-Control-Allow-Credentials', true); // If needed
res.send('cors problem fixed:)');
});
The top answer worked fine for me, except that I needed to whitelist more than one domain.
Also, top answer suffers from the fact that OPTIONS request isn't handled by middleware and you don't get it automatically.
I store whitelisted domains as allowed_origins in Express configuration and put the correct domain according to origin header since Access-Control-Allow-Origin doesn't allow specifying more than one domain.
Here's what I ended up with:
var _ = require('underscore');
function allowCrossDomain(req, res, next) {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
var origin = req.headers.origin;
if (_.contains(app.get('allowed_origins'), origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
if (req.method === 'OPTIONS') {
res.send(200);
} else {
next();
}
}
app.configure(function () {
app.use(express.logger());
app.use(express.bodyParser());
app.use(allowCrossDomain);
});
The answer code allow only to localhost:8888. This code can't be deployed to the production, or different server and port name.
To get it working for all sources, use this instead:
// 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();
});
Install cors dependency in your project:
npm i --save cors
Add to your server configuration file the following:
var cors = require('cors');
app.use(cors());
It works for me with 2.8.4 cors version.
Hi this happens when the front end and backend is running on different ports. The browser blocks the responses from the backend due to the absence on CORS headers. The solution is to make add the CORS headers in the backend request. The easiest way is to use cors npm package.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
This will enable CORS headers in all your request. For more information you can refer to cors documentation
https://www.npmjs.com/package/cors
This worked for me.
app.get('/', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.send('hello world')
})
You can change * to fit your needs. Hope this can help.
All the other answers didn't work for me. (including cors package, or setting headers through middleware)
For socket.io 3^ this worked without any extra packages.
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
app.all('*', function(req, res,next) {
/**
* Response settings
* #type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
Add following code in app.js of NODEJ Restful api to avoid "Access-Control-Allow-Origin" error in angular 6 or any other framework
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
//enables cors
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
You could use cors package to handle it.
var cors = require('cors')
var app = express()
app.use(cors())
for setting the specific origin
app.use(cors({origin: 'http://localhost:8080'}));
know more
You can use "$http.jsonp"
OR
Below is the work around for chrome for local testing
You need to open your chrome with following command. (Press window+R)
Chrome.exe --allow-file-access-from-files
Note : Your chrome must not be open. When you run this command chrome will open automatically.
If you are entering this command in command prompt then select your chrome installation directory then use this command.
Below script code for open chrome in MAC with "--allow-file-access-from-files"
set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
set switch to " --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"
second options
You can just use open(1) to add the flags: open -a 'Google Chrome' --args --allow-file-access-from-files
/**
* Allow cross origin to access our /public directory from any site.
* Make sure this header option is defined before defining of static path to /public directory
*/
expressApp.use('/public',function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
// Request headers you wish to allow
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// Set to true if you need the website to include cookies in the requests sent
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
/**
* Server is about set up. Now track for css/js/images request from the
* browser directly. Send static resources from "./public" directory.
*/
expressApp.use('/public', express.static(path.join(__dirname, 'public')));
If you want to set Access-Control-Allow-Origin to a specific static directory you can set the following.
Apart from all listed answers, I had the same error
I have both access to frontend and backend, I already added cors module app.use(cors()); Still, I was struggling with this error.
After some debugging, I found the issue. When I upload a media which size was more than 1 MB then the error was thrown by Nginx server
<html>
<head>
<title>413 Request Entity Too Large</title>
</head>
<body>
<center>
<h1>413 Request Entity Too Large</h1>
</center>
<hr>
<center>nginx/1.18.0</center>
</body>
</html>
But in the console of frontend, I found the error
Access to XMLHttpRequest at 'https://api.yourbackend.com' from origin 'https://web.yourfromntend.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
So It makes confusion here. But the route cause of this error was from nginx configuration. It's just because the directive client_max_body_size value has been set to 0 by default. It determines what the allowable HTTP request size can be is client_max_body_size. This directive may already be defined in your nginx.conf file located at /etc/nginx/nginx.conf Now you need to add/edit the value of the directive client_max_body_size either at http or server.
server {
client_max_body_size 100M;
...
}
Once you have set your desired value, save your changes and reload Nginx: service nginx reload
After these changes, It's working well
REFERENCE: https://www.keycdn.com/support/413-request-entity-too-large#:~:text=%23,processed%20by%20the%20web%20server.&text=An%20example%20request%2C%20that%20may,e.g.%20a%20large%20media%20file).
We'll see if the top 2 answers accept my edit, but it's very likely you're gonna have to either add or use 127.0.0.1 instead of localhost.
With the cors package, you're even able to use more than one allowed origin:
app.use(
cors({ origin: ["http://localhost:8888", "http://127.0.0.1:8888"] })
);
And you could use origin: "*" if you wish to allow for anything.
For more info, do check out Web Dev Simplified's tutorial.

Resources