i have deployed a nodejs express server to heroku, and when i try to use it i get back the error -
"Access to XMLHttpRequest at 'https://harel-shop-backend.herokuapp.com/auth/autologin' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
in the browser.
this is my app.ts code -
import './db/mongoose';
import HttpError from './model/http-error';
import cors from 'cors';
import authRoutes from './routes/auth.router';
import productRouter from './routes/product.router';
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization ,AuthorizationRefresh ,user'
);
res.setHeader(
'Access-Control-Allow-Methods',
'OPTIONS, GET, POST, PATCH, DELETE'
);
next();
});
app.use('/auth', authRoutes);
app.use('/products', productRouter);
app.use((req, res, next) => {
throw new HttpError('couldnt find this route', 404);
});
app.use((error: any, req: Request, res: Response, next: NextFunction) => {
if (res.headersSent) {
return next(error);
}
res.status(error.code || 500);
res.json({ message: error.message || 'an unknown error occurred' });
});
app.listen(3030, () => {
console.log('server is running');
});
i have tried to install extensions to my browser to disable cors but didnt work ,
i tried to add the ('Access-Control-Allow-Origin', '*')
but also didnt work.
installed the cors package and used in the line 10 , also didnt work
CodePudding user response:
So i fixed the problem and i did 2 things ,
- Made a dist folder with npm build and added a Procfile and wrote there -
web: node dist/app.js
- I also added
process.env.PORT || 3030
to the app.listen function