I have a server in node.js - Express. When I make a fetch request I get this error displayed in the console:
Access to fetch at 'http://localhost:3000/home' (redirected from 'http://localhost:8000/auth/google/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
CORS
I have researched this for a while and have tried the solutions sugested that help most people. This is not my first server, I've done this before and everything worked out fine. All I've had to do was this app.use(cors());. However, that is not working.
I've also tried the below solutions:
1.
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
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();
});
On the front end, in the fetch request I added this (even tho it's default)
{ mode: 'cors' }.
app.options(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
- And I've tried a bunch of variations similar to 1, 2, and 4... which I shouldn't have to do because
app.use(cors());should be enough. Yes, I am adding my middleware BEFORE my routes.
Server App.js file
// --- requirements ---
require('dotenv').config();
const express = require('express');
const authRoutes = require('./routes/auth-routes');
const morgan = require('morgan');
const cors = require('cors');
const helmet = require('helmet');
const { NODE_ENV } = require('./config');
const passportSetup = require('./config/passport-setup');
const keys = require('./config/keys')
const cookieSession = require('cookie-session');
const passport = require('passport');
// --- middleware ---
const app = express();
const morganOption = (NODE_ENV === 'production')
? 'tiny'
: 'common';
app.use(morgan(morganOption));
app.use(helmet());
//I've also placed this line right below "const app = express();"
app.use(cors());
//I removed all of my other attempts for cors
//makes sure the cookie is just a day long
app.use(cookieSession({
maxAge: 24*60*60*1000,
keys: [keys.session.cookieKey]
}));
//init passport
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth', authRoutes);
// --- endpoints ---
app.get('/', (req, res) => {
console.log("GET /");
res.send('Hello, world!')
});
app.use((error, req, res, next) => {
let response
if (NODE_ENV === 'production') {
response = { error: { message: 'server error' }}
} else {
response = { error }
}
res.status(500).json(response)
})
// --- export ---
module.exports = app;
Since I've never had this issue with cors before, I decided to make a simple request GET request to '/' and send "Hello World" back. Even doing that I got the same issue. I'm lost, the solutions I've read online don't help.
If anyone has any idea why app.use(cors()); and the other related solutions I've used haven't been working or know of a way that will work, please let me know.
I really do want to understand why my way isn't working because it's worked many times before.
Thank you!
EDIT (fetch code was requested):
A lot of the code that I haven't shown doesn't matter, I know this because I've isolated the issues which is why I'm only showing a portion of my server code and none of my client code. Showing all the code will require me to go into more detail on how it's not essential, and in my experience, the longer and more confusing the question becomes the less likely you are to get an answer.
However, since this has been requested I will do some clarifying to save time.
Yes, originally I am was trying to send a url back to the client from the server via res.redirect(). However, I've tried returning a status res.status() or even just res.send('hello world') and I've received the error, so the issue is not with me trying to redirect.
On the front end side, there are some headers in my code that may not need to be there, trust me, I've removed some, all, and added others. The headers are not contributing to the issue.
Also, I realize that one of my headers is the application/json and when you are redirecting from the server, it isn't necesary. I've tried removing it and removing .json().
Here's the code:
fetch('http://localhost:8000',
{ method: "GET", redirect: "follow", 'content-type': 'application/json'})
.then(res => {
console.log('fetched');
if(!res.ok){
console.log('error:', res);
}
return res.json(); //this is where the error occurs
})
.then(res => {
console.log('succsess: ', res);
})
.catch(err => {
console.log('ERROR: ', err);
})