Angular从express js访问google auth时出现错误



错误:从'http://localhost:5000/auth/google'重定向)从原点'http://localhost:4200'已被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'标头。

即使我在服务器上使用cors模块,我也会得到这个错误。

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

也试过这个,而不是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

当我点击login with google button这个servicemethod将被执行

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

试试下面-

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

在您的快递服务中:

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

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

确保在调用其他路由之前调用app.use((req, res, next) => {}

相关内容

最新更新