Home > Enterprise >  Angular cors error while accessing google auth from express js
Angular cors error while accessing google auth from express js

Time:09-26

Error: redirected from 'http://localhost:5000/auth/google') from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

even though i am using cors module in server i am getting this error.

const cors = require('cors')
app.use(cors())

Tried this one also instead of cors

app.use((req, res, next) => {
    console.log("entered cors")
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET , PUT , POST , DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type, x-requested-with");
    next();
})

my service code in angular

When i click login with google button this servicemethod will get executed

addGoogleUser():Observable<any>{
  const headers = new HttpHeaders()
  headers.set('content-type','application/json')
  return this.http.get("http://localhost:5000/auth/google",{headers:headers});
}

CodePudding user response:

In your express service:

res.header("Access-Control-Allow-Origin", '*');

Or

res.header("Access-Control-Allow-Origin", "http://localhost:4200");

And make sure you call app.use((req, res, next) => {} before calling your other routes.

CodePudding user response:

Try below -

app.get('/auth/google', cors(), (req, res) => {
        // your get code
 });
  • Related