I have been having some issues with my node.js server. I launched it using heroku and now I want my chrome extension to send http requests to the server (using cookies).
I am using express.js as my backend and I am having trouble setting up CORS the right way.
This is what I have in app.js:
if (process.env.NODE_ENV !== 'production') {
app.use(cors({
credentials: true,
origin: ['http://localhost:4200', 'http://localhost:8000', 'chrome-extension://kdfekbilmpafgiocanhihiogknfilcio']
}));
} else {
app.use(cors({
credentials: true,
origin: ['chrome-extension://kdfekbilmpafgiocanhihiogknfilcio']
}));
}
app.use(session({
secret: 'angular shhh secret auth',
resave: true,
saveUninitialized: true,
cookie : {
httpOnly: true,
expires: new Date(253402300000000)
}
}));
and I am making requests from my chrome-extension (client) like this:
signUp(user) {
const options = { withCredentials: true };
return this.myHttp.post(`${this.BASE_URL}/signup`, user, options)
.toPromise()
.then((result) => {
result.json()
});
}
Aaand this is my error:
XMLHttpRequest cannot load
https://moodflowextension.herokuapp.com/loggedin. 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:4200' is therefore not allowed access. The
credentials mode of requests initiated by the XMLHttpRequest is
controlled by the withCredentials attribute.
I know I should pass in the cookie in the header somehow...
Sessions and credentials require higher security in the form of not having wildcards in your header.
Fortunately, there is a way around this.
var whitelist = [/yourDomain/];
var corsOptions = {
origin: whitelist
};
app.use(cors(corsOptions));
This will make CORS only allow origins that contain yourDomain (which is a regexpression btw, not a string), without breaking credentials and sessions.