I'm currently building an SPA - React frontend, hosted on Netlify and NodeJS backend, hosted on Heroku.
I've been building it for a few weeks and it works perfectly fine on my Macbook. Today I tried to put it on 'servers', (Heroku + Netlify) and came across an issue, which I think is triggered by the CORS. The main issue is that, the server hosted version isn't receiving the cookies, passed on by the React App axios requests.
Here's the server side code I've written:
const WhiteList = [
'http://localhost:3000',
'https://example.netlify.app'
]
var corsInit = (req, callback) => {
var corsOptions;
console.log(req);
console.log(req.header('Origin'));
if(WhiteList.indexOf(req.header('Origin')) !== -1){
console.log('matched')
corsOptions = {
origin: true,
optionsSuccessStatus: 200,
credentials: true,
preflightContinue: true
}
} else {
console.log('no match')
corsOptions = {origin: false}
}
callback(null, corsOptions)
}
//Load ExpressJS & Dependencies
const express = require('express');
const app = express();
const cors = require('cors');
var cookieParser = require('cookie-parser');
//Middleware
app.use(express.json());
app.use(cookieParser());
app.use(cors(corsInit));
const accountRouter = require('./accountRouter');
// account router js file
router.route('/userData')
.get(account_controller.GetUserData)
// controlle js file
exports.GetUserData = (req, res) => {
let token = req.cookies.app_token;
console.log(req.cookies); // On nodejs running locally, it returns all cookies on my browser - Hosted version (heroku) returns null or [Object: null prototype] {} to be exact, which is causing errors.
...... rest of the code };
On the client side (React) I'm using axios and it's configured in its own api.js file.
import axios from 'axios';
// export default axios.create({
// baseURL: `http://localhost:7000/api/`,
// withCredentials: true
// });
export default axios.create({
baseURL: `https://example.herokuapp.com/api/`,
withCredentials: true
});
Been on this since last night, but nothing seems to be working. Any suggestions?
Thanks!