I have an application built on angular and node js and when after login into application, there is an error on fetching data as it is shown me CORS error? how should I resolve this error?
Asked
Active
Viewed 426 times
0
-
1Please read this tutorial https://medium.com/@alexishevia/using-cors-in-express-cac7e29b005b – Babar Hussain Sep 15 '19 at 21:00
-
Possible duplicate of [CORS error on same domain?](https://stackoverflow.com/questions/19966707/cors-error-on-same-domain) – sunknudsen Sep 15 '19 at 21:18
2 Answers
0
The problem is probably caused by the API running on a different port. See CORS error on same domain?
Try adding Access-Control-Allow-Origin
and Access-Control-Allow-Methods
headers to your API.
This is how this is achieved on Express using middleware.
The following allows all origins and methods (this might be too open depending on your requirements).
const express = require('express');
const app = express();
const port = 3000;
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
next();
});
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

sunknudsen
- 6,356
- 3
- 39
- 76
-
-
@Vinhaariqbal Can you try replacing the `server.opts('/\.*/', corsHandler, optionsRoute);` lines by the above `app.use` code block (replacing `app` by `server`)? – sunknudsen Sep 16 '19 at 10:57
-
@Vinhaariqbal Also, I recommend using environment variables instead of hard coding passphrases. See https://www.npmjs.com/package/dotenv – sunknudsen Sep 16 '19 at 10:59
-
Yes this is the production code, and i try your advise and let you know. – Vinhaar iqbal Sep 16 '19 at 11:03
-
@Vinhaariqbal It’s probably a good idea to change the passphrase as it was just leaked in the above link. – sunknudsen Sep 16 '19 at 11:05
-
-
0
This error is due to app running on port 1949 rejecting the request from port 80, bcos it considers as cross origin request. You need to config CORS for the app on port 1949 to access from any origin origin: "*"
, sample for node js:
server.use(
cors({
origin: "*",
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
})
);

Vengleab SO
- 716
- 4
- 11
-
I update my answer, you don't need to set header at ur own, just config the cors is enough – Vengleab SO Sep 16 '19 at 07:15
-
So I remove all my CORS function and replace it with the code you provide above? – Vinhaar iqbal Sep 16 '19 at 07:20