CORS preflights error when using redirect - express

I`m trying to realize redirecting to another page of my app (current location 'http://localhost:3000/create-item' redirect to 'http://localhost:3000/subscribe') after saving item to database on my express server using next code (client send POST message to endpoint with form data):
await item.save();
res.writeHead(302, { Location: 'http://localhost:3000/subscribe' });
res.end();
one more variant:
await item.save();
res.redirect('/subscribe');
In base file of my server index.js i use my custom CORS middleware:
//cors.middleware.js
function cors(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, PATCH, POST, DELETE, OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization',
);
next();
}
module.exports = cors;
//index.js
const corsMiddleware = require('./middleware/cors.middleware');
app.use(corsMiddleware);
I also tryed:
npm i cors
app.use(cors());
Nevertheless I recieve CORS error while redirecting. So, what I`m doing wrong? Maybe this is related to sending data with POST method (redirect inside GET endpoint working well without CORS erro)

Related

Authorization using Vue.js and Express,js

I have a problem with my Vue.js app. I have an Express backend and a authorization on it and i use passport.js to make it.
Next i have Vue.js application where should be pages that cant be open if user is not authorized and i want to check it.
I try to use cookies but after some variants i finally confused about it. My browser is saving cookies for my server, and i cant read it on client because "http-only" flag, and i cant check authorization with a get request becase idk (there is no cookies on client?).
So, what is a best way to make it?
So i add a header in Express like that
const allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Headers', 'origin, content-type, accept');
res.header('Access-Control-Allow-Credentials', true);
next();
}
app.use(allowCrossDomain);
then
check authorization
axios.get('url',{withCredentials:true})
and login
axios.post('login',{withCredentials:true})
like that

Authorization header not passed on even tho it's allowed

I'm unable to retrieve Authorization header from requests where I send with CORS even though I've allowed 'Authorization' in 'Access-Control-Allow-Headers'. Sending with postman works.
Tried multiple different request methods including: request, axios and qwest. None of them work.
//Access Control in index.js before route.
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers, Cache-Control");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT")
next();
});
Expected result: Getting data back.
Actual output:
403 error forbidden because server can't get authorization header and error: 'Access to XMLHttpRequest at 'http://localhost:5000/api/cases/list?page=1&size=10' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.'
Switching to the cors module for express solved my issue. I replaced that whole block with
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"allowedHeaders": ['Authorization', 'Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Access-Control-Request-Method', 'Access-Control-Request-Headers', 'Cache-Control']
}))
which works. Really weird issue but I'm not gonna keep trying to figure out why it doesn't work.

How to remove these swagger warnings, about HEAD and OPTIONS?

I used swagger on express js and when I do a query I am getting this warnings.
WARNING! Unable to find a Swagger operation that matches HEAD ... - this will show if I will try to use curl.
WARNING! Unable to find a Swagger operation that matches OPTIONS ... - while this one is when accessed from a webpage.
I already add helmet and this to the code.
app.use((_, res: Response, next: NextFunction) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
res.header(
'Access-Control-Allow-Headers',
'Content-Type, api_key, Authorization',
);
next();
});
What I miss?
Finally got it working, I mean the warning is not showing anymore. The solution is just a one liner, sending HTTP status of 200 telling the browser that the request is supported.
export function optionCORS(req: Request, res: Response, next: NextFunction): void {
// I am just setting the headers if the request is an OPTION or HEAD
// For now I didn't interfere with the other request like POST, etc.
// I have a guess that swagger is is doing it.
if (req.method === 'OPTIONS' || req.method === 'HEAD') {
const origin: string = req.headers.origin as string;
// On my angular I have interceptor that will set the ```withCredentials```
// option to true, so I cant use * on Allow-Origin so I grab the
// request.headers.origin an used it.
// Also we need to set the Allow-Credentials to true.
res.header('Access-Control-Allow-Origin', origin);
res.header('Access-Control-Allow-Credentials', 'true');
// Then the usual headers.
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'Accept, Authorization, Content-Type, Content-Length, Origin, ' +
'X-Requested-With',
);
// And this what I miss, just the HTTP 200 status.
// So the client will know that the request is supported.
res.sendStatus(200);
return;
}
// If the request is not an OPTIONS or HEAD continue as usual,
// it look like swagger is handling it.
next();
}
Then you can use it as middleware.
app.use(optionCORS);
If you using swagger-express-middleware set WARN=off environment variable
https://github.com/APIDevTools/swagger-express-middleware/blob/ed73f82e57adb868b10e1989dac555b8d943dab8/lib/helpers/util.js#L27

No 'Access-Control-Allow-Origin' header is present on the requested resource (express + react/redux) [duplicate]

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
(36 answers)
Closed 4 years ago.
I'm getting this error on my React app. "Failed to load https://app-name.herokuapp.com/users/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access."
Code in my Express app
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, X-Auth-Token, Accept");
next();
}
Code in my Redux fetch call
return dispatch => {
const url = "https://app-name.herokuapp.com/users/";
return fetch(url, {
method: 'GET',
mode: 'cors',
})
.then(handleErrors)
.then(res => res.json())....
That's an issue with your WebService, that happens when you are pointing from a domain to a different domain, like I'm pointing from localhost:3000 to localhost:3001, those are different, you should enable CORS in your WebService to allow that request.
You have to look for a way to enable CORS in your Heroku app, as I know, the external API calls are blocked in free domains, but don't know with Heroku.
I figured it out. All I had to do was push to my heroku app. I didn't know it had its own git repo. Facepalm.

Request header field Authorization is not allowed by Access-Control-Allow-Headers Error

I have a VueJS application and a ExpressJS server side application. On my server I have the following:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
}
app.use(allowCrossDomain);
However, I keep getting the following error:
Request header field Authorization is not allowed by
Access-Control-Allow-Headers in preflight response.
I'm sending my request like this:
import axios from 'axios'
export default axios.create({
baseURL: 'https://example.com',
timeout: 5000,
headers: {
'Authorization': 'Bearer ' + accessToken
}
})
How can I get around this? I have tried many solutions and read up on this. I have read the below:
How to allow CORS?
CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response
The code in the question apparently isn’t causing the Access-Control-Allow-Headers header to get sent for OPTIONS responses — specifically, for the response to the CORS preflight OPTIONS.
To ensure preflight OPTIONS get handled correctly, consider installing the npm cors package:
npm install cors
And then do something like this:
var express = require('express')
, cors = require('cors')
, app = express();
app.options('*', cors()); // preflight OPTIONS; put before other routes
That will handle CORS preflight OPTIONS requests and other CORS aspects without you needing to manually write your own handling from scratch in your application code.
https://www.npmjs.com/package/cors#configuration-option has more details on all the options.