Reputation: 171
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?
Upvotes: 16
Views: 75756
Reputation: 7067
I may be late, but it may be helpful to someone else.
I have faced the same issue in Heroku related to the CORS. I have tried all the combinations of origin and many other workarounds in cors.
But later I found that it is an issue in TypeScript compilation.
In the tsconfig.json
file, I have set incremental
to true
, which does not generate the js files that caused this issue.
So, for each request, Heroku sends 503 error messages.
You can use the activity tab or logs from Heroku. Attached is the screenshot below:
Upvotes: 0
Reputation: 553
I had the same cross error but
In my case what i needed was simply making sure the backend server (on Heroku) was running fine by viewing the logs from settings (on Heroku app setting) you can also check the logs via this command line heroku logs --tail
Upvotes: 0
Reputation: 1
I had the same issue after deploying in Heroku, using console.log() in different points of the code, I could see an error message like this: 'RangeError Maximum call stack size exceeded...'. It was a NodeJs bug, I fixed it by adding this code at the bottom of my package.json:
"resolutions": { "fs-capacitor": "3.0.0" }
let me know if it works for you.
Upvotes: 0
Reputation: 11
I had a similar issue with Heroku and my backend, which was hosted in vercel in now.
If you are using environment variable make sure you set those in your vercel app, or if you're hosting anywhere else check that before anything else. ENV VARIABLES!
Upvotes: -4
Reputation: 179
Your issue is related to Service Unavailable from the CORS Heroku server. Since it is a free service, the number of calls per hour is limited to 50. Please try to use your own CORS server as a middleware as suggested in the answers or self host CORS-Anywhere
Upvotes: -1
Reputation: 321
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:
503 Service Unavailable
as indicated below, that is an indication again that your code is breaking.Upvotes: 9
Reputation: 1109
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!.
Upvotes: 1
Reputation: 1838
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;
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)
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.
I have some recommends for your code:
User.findOne()
instead of User.find()
app.use(cors());
jsonwebtoken
should use Asynchronous instead of Sync when run on server.Upvotes: 13