I have a Single Page Application(SPA) using axios that tries to get information from a ExpressJS Api running on the same server.
In the SPA axios settings I have the following:
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': store.getters.token,
'user': store.getters.user
},
and in the API i am using the npm package cors like this:
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
const indexRouter = require('./routes/index');
const adminRouter = require('./routes/adminRoute');
// More routes
app.use('/api', indexRouter);
app.use('/api/admin', adminRouter);
app.use('/api/user', userRouter);
// using more routes
This works fine when running locally, but when putting the api on a server (using a node application) I get CORS errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at mysite.com. (Reason: CORS request did not succeed).
I can access the api directly from browser and get a response without problems (since it isn't using cross reference) but at least I know the API is running.
I have tried creating the following (before I define my routes) instead without success:
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();
});
What am I doing wrong?
It's really strange, to allow anything you have to just write app.use(cors()) and it should work probably now it dont work because after app.use(cors()) you write:
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();
});
then you should try with just cors() middleware. In order to set cors properly check cors`s documentation.
Documentation
The reason why this did not work was because the web hotel where I hosted my ExpressJS api had not set up their nginx web server proxy so that it could accept the OPTIONS request properly and return with Access-Control-Allow-Origin: api.site.com
If you need more information regarding the setup of cors have a look at these links
CORS express not working predictably
How do I host a web application and an API from the same server while keeping them in separate?
Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests
Related
I tried every answer but still I am getting the same error. Here is my firebase functions code -
const functions = require("firebase-functions");
require("dotenv").config();
const cors = require("cors");
const express = require("express");
const bodyParser = require("body-parser");
const routes = require("./routes");
const app = express();
app.use(bodyParser.json());
app.use(routes);
app.use(cors({ origin: true }));
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Max-Age", "1800");
res.setHeader("Access-Control-Allow-Headers", "content-type");
res.setHeader(
"Access-Control-Allow-Methods",
"PUT, POST, GET, DELETE, PATCH, OPTIONS"
);
next();
});
exports.myfunction = functions.https.onRequest(app);
This function works properly in 'Postman' but whenever I try to call this function from my react application, it shows this error --
Access to XMLHttpRequest at 'https://us-central1-monday-demo-24354.cloudfunctions.net/mondaybaseurl/demo/sheets/37477045' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Can somebody please tell me what going wrong here?
My reactjs website runs on https and my NodeJS server is https but I got error calling the NodeJS api from reactjs website. Both ReactJS website and NodeJS api deployed on the same linux VPS server, my database is on a remote but the connection is fine as I am not getting database connection error but i got cors errors like below:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8184/api/v1/signin. (Reason: CORS request did not succeed). Status code: (null).
My NodeJS that started the https server enable cors and it allowed cross origin. See my NodeJS
const cors = require('cors')({
origin: 'https://mydomaindotcom'
});
const allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT,PATCH, DELETE, OPTIONS, ');
res.header('Access-Control-Allow-Credentials', false);
res.header('Access-Control-Max-Age', '86400');
res.header('Access-Control-Allow-Headers', 'Authorization, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
};
app.use(allowCrossDomain);
// Error logger
app.use(logger('dev', {
skip: function (req, res) { return res.statusCode < 400 },
stream: fileWriter
}))
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cors);
app.use(fileUpload());
app.use("/api/v1", routes);
In my ReactJS package.json file i have my domain as homepage like below:
"homepage": "https://mydomain",
"Hostname": "https://mydomain",
Please help on this cors errors, it has taken enough sweat on my face.
I implemented a basic express app for cloud functions. I have used the cors library to enable cors. There are 4 api endpoints and all 4 need to be preflighted. For some reason, access-control-allow-origin:* header is placed on the 3 routes and not the 4th one.
Precisely, i'm using Content-Type: application/json for POST requests, which need to be preflighted. All the endpoints need the same headers, but it isn't applied for the last one.
Code snippets:
const express = require("express");
const cors = require("cors");
const bodyParser = require('body-parser');
const admin = require("firebase-admin");
admin.initializeApp();
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(express.json());
app.use('/', require('./controllers'));
exports.apiv2 = functions.https.onRequest(app);
Routes:
const express = require('express');
const router = express.Router();
router.use('/create-player', require('./createPlayer'));
router.use('/create-game', require('./createGame'));
router.use('/join-game', require('./joinGame'));
router.use('/move', require('./makeMove'));
// 404 error handler for invalid player and game IDs
router.use((err, req, res, next) => {
res.json({ error: err.msg });
});
module.exports = router;
For the /move route alone, the cors request fails, even after preflight request passes. Preflight passes with 204. The actual request fails for some reason. The POST request fails
Is there any particular access control header is not placed by express for one endpoint alone ?
You can set this middleware before your routes middleware in app.js to solve thi problem:
// app.js
...
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', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if ('OPTIONS' === req.method)
res.sendStatus(200);
else
next();
});
...
app.use(routes);
Then, this will be applied for all of your routes.
I'm developing a Webapp using React-Redux, making request to a API in nodejs in a different domain.
To login the user, I send the credentials to my API, which validates them and sends me back as JWT. I'm trying to do this by using the ExpressJS, so in the login path in my API I have:
res.cookie("my_token", token);
The problem is that the Cookie is not being added to the session. Using Mozilla, I can see that the Set-Cookie property it is in the headers with the right cookie, but it doesnt show up in my resources.
I also made some tests with DHC, using DHC the Cookie is successfuly stored in my session cookies.
I have
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
in both my website and api. In the website I'm using react module axios to make the requests. In the api I'm using cookie-parser to handle the cookies. These are my middlewares (both api and app):
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
const cookieParser = require("cookie-parser");
app.use(cookieParser());
const bodyParser = require("body-parser");
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
const morgan = require("morgan");
app.use(morgan('dev'));
This is my request:
axios.post(`${ROOT_URL}/login`, creds)
.then(res => { /*...*/ })
.catch(err => { /*...*/ });
This is my response:
res.cookie("session_token", token, { domain: ".mydomain.com" }).send(response);
I have a similar problem with Angular code, Thing I dids to solved
From the client you need enable withCredentials I thing axios should have some option to enable it
From your backend res.header("Access-Control-Allow-Origin", "*"); is not enough
You can do something like this
res.header("Access-Control-Allow-Origin", req.header('Origin'));
Because you need return a host not an asterisk, this is only for development purposes, I recommend you change this to some static url later
I am trying to build an application with angularjs as front end and rest api using express js. I built both the projects using yeoman and my angular app is running on localhost:9000 and my express app is running on localhost:3000. When i try to talk to express js app from angular, I am getting a cross domain request, is there any way to fix this.
app.js in Express App
var routes = require('./routes/signup')(app); //This is the extra line
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "{GRUNT_SERVER}");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
app.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.js in angularjs app
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.withCredentials = true;
Error
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:9000' is therefore not allowed access.
The response had HTTP status code 409.
EDIT
Here's the code that I added to my app.js file:
// allow CORS:
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
next();
});
This also throws the same error ("No 'Access-Control-Allow-Origin' header is present on the requested resource.") as before.
EDIT
After using
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
This is throwing POST localhost:3000/signup 409 (Conflict)
Use npm cors - https://github.com/expressjs/cors to allow cors request.
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
app.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.listen(3000);