CORS problems on HEROKU
Solution 1
You've cross origin domain on https://whispering-shore-72195.herokuapp.com from origin https://mighty-citadel-71298.herokuapp.com
You can try npm cors package as middleware instead of your custom middleware. CORS
package allows you multiple configure and it's very easy to use.
Simple Usage (Enable All CORS Requests)
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
require('dotenv').config()
import filmRoutes from './api/routes/films'
import userRoutes from './api/routes/users'
const app = express()
const DBNAME = process.env.DB_USER
const DBPASSWORD = process.env.DB_PASS
mongoose.connect(`mongodb://${DBNAME}:${DBPASSWORD}@ds157422.mlab.com:57422/filmbase`, {useNewUrlParser: true})
/*app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});*/
app.use(cors()); // <---- use cors middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/films', filmRoutes)
app.use('/users', userRoutes)
export default app;
Edit:
I've test your client call login to your server from https
and it's working without CORS problem. Maybe you had fixed it successfully.
I've tried with simple on StackBlitz and it's working successfully.
You can try login https://js-53876623.stackblitz.io/ and view network tab when inspecting and see OPTIONS (200 status)
and POST (404 not found)
(because I don't know any user in your database)
Edit Dec 22 2018 - 7:18 PM
I've tried your code on my local, maybe you hadn't tested and handled all error, it makes your app crash unfortunately.
I've run your code and noticed the problem maybe jsonwebtoken
error:
Error: secretOrPrivateKey must have a value
Please tried with process.env.JWT_KEY || 'Require key here!!!',
, and set your JWT_KEY
on your environment or use ||
as default key on server.
Maybe it will fix your problem.
Recommends:
I have some recommends for your code:
- Please use
User.findOne()
instead ofUser.find()
- Please use
app.use(cors());
-
jsonwebtoken
should use Asynchronous instead of Sync when run on server.
Solution 2
You need to determine if it is indeed a CORS issue or your API code is breaking.
If it's a CORS issue, handle CORS in your backend code like it's been suggested above or use the cors
package.
However, often times than not, the issue is that your code is breaking and you just didn't know. In my case, for instance, I didn't add nodemon
to the dependencies and my start
script is dependent on nodemon
which Heroku could not find. So it's possible that your code works fine in dev but breaks in prod.
Here's how you can find what part of your code is breaking within Heroku:
- Inspect your network in your browser dev tool. If the response is
503 Service Unavailable
as indicated below, that is an indication again that your code is breaking. - Locate the More button on the top right corner of your Heroku dashboard once you open the project you're having issues with.
- Select View Logs from the dropdown that shows up after you click the More button. You should now see the log of the track trace. If you don't see the error, try making any small change in your code and redeploying while watching the log again. In my case, as indicated below, the nodemon was the reason for the crash.
Solution 3
I have deal with same problem, I think your problem is not CORS. Can you test your server logs. In my case i had a package problem and thats way i was getting 503 also No 'Access-Control-Allow-Origin' header, CORS error. When i fix package and jwt problem my CORS problem solved!.
misu jakis
Updated on July 09, 2022Comments
-
misu jakis almost 2 years
I have problem with CORS on Heroku.
This is my code on server
import express from 'express'; import bodyParser from 'body-parser'; import mongoose from 'mongoose'; require('dotenv').config() import filmRoutes from './api/routes/films' import userRoutes from './api/routes/users' const app = express() const DBNAME = process.env.DB_USER const DBPASSWORD = process.env.DB_PASS mongoose.connect(`mongodb://${DBNAME}:${DBPASSWORD}@ds157422.mlab.com:57422/filmbase`, {useNewUrlParser: true}) app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", '*'); res.header("Access-Control-Allow-Credentials", true); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json'); next(); }); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use('/films', filmRoutes) app.use('/users', userRoutes) export default app;
This is my post request
CheckLogin = () => { const data = { name: this.state.formInput.login.value, password: this.state.formInput.password.value } axios.post('https://whispering-shore-72195.herokuapp.com/users/login', data) .then(response=>{ console.log(response); const expirationDate = new Date(new Date().getTime() + response.data.expiresIn * 1000) localStorage.setItem('token', response.data.token) localStorage.setItem('expirationDate', expirationDate) this.context.loginHandler() }) .catch(err=>{ console.log(err) }) console.log(data); }
This is ERROR
Access to XMLHttpRequest at 'https://whispering-shore-72195.herokuapp.com/users/login' from origin 'https://mighty-citadel-71298.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tried a lot of methods and nothing... any idea?
-
misu jakis over 5 yearsi tried cors package at the first time and still the same problem
-
Ha. Huynh over 5 yearsI've test your client code with simple demo and it's working now. I've updated my answer
-
misu jakis over 5 yearsif you put a wrong values then status will be 404, but if you put a correct values then still is cors problem... ?
-
Ha. Huynh over 5 yearscan you share an user and password for testing?
-
misu jakis over 5 yearslogin: olosls pass: tester
-
Ha. Huynh over 5 yearsI think it's not a problem of CORS. Please check your code handling login, I think it has error, because 503 is server error, not related to CORS
-
misu jakis over 5 yearsi watching logs in heroku and, first time when the values is worng the logs throw staus 200 and then 404. but if i push wrong values in the logs i see, only status 503 and app crashed.
-
Ha. Huynh over 5 yearsyour handle incorrectly and it make app crash, please share your code
-
misu jakis over 5 yearsi shared, any feedback?
-
misu jakis over 5 yearsYep, i forgot that .env is in .gitignore but i found another bug too, i had wrong export in userController.
-
nbpeth over 3 yearsI swear to god, I was missing the parens on
app.use(cors)
-
germanio about 3 yearsWait... could you clarify your answer? the question has nothing to do with vercel, it's a CORS issue between two Heroku domains.
-
Orlando Rivera about 3 years@germanio I was just sharing my findings with this issue. As I was researching I was coming across this post over and over again so I thought anyone coming across this same issue could benefit, but I should probably open up a new thread. The issue was with the environment variables. Also I found better luck hosting the Front End from Netlify since CORS was never an issue there, if you specified the request origin.