如何从Angular cli调用passportjs(node)API?

时间:2018-02-05 05:57:16

标签: angularjs node.js angular angular-cli passport.js

使用passportJS OAuth2配置和运行NodeJ,但是要求是angular应该调用节点api,两者都在不同的端口中运行,从angular调用所有nodeJS的其余API,并且使用代理运行正常。 conf.json,同时从角度获取错误响应中调用/googleauth/redirect

回应:

Failed to load https://accounts.google.com/o/oauth2/v2/auth?response_type=code... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Google API设置:

限制

授权的JavaScript起源:

http://localhost:4200
http://localhost:8088

授权重定向URI:

http://localhost:4200/api/googleauth/redirect
http://localhost:8088/api/googleauth/redirect

更新1:CORS到app.js(新):但没有变化。

var cors = require('cors');
var app = express();
app.use(cors());
app.options('*', cors());
app.use('/api',cors(),require('./routes/api'));

更新2:api.js

router.get('/google', passport.authenticate('google', { scope: ['profile','email'] }));

护照设置

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20');
const userModel = require('../model/user');

passport.serializeUser((user,done)=>{
  done(null,user.id);
});

passport.deserializeUser((id,done)=>{
  userModel.findById(id).then((user)=>{
    done(null,user);
  })
});

passport.use(
  new GoogleStrategy({
    callbackURL:'/api/googleauth/redirect',
    clientID:'',
    clientSecret:''
  },(accessToken,refreshToken,profile,done) =>{
    console.log("call back function fired");
    //console.log(accessToken);
    userModel.findOne({email:profile.emails[0].value,authType:'google'},function(err,user){
        if(user){
          done(null,user);
        }else{
          done(null,user);
        }
    });
  }))

1 个答案:

答案 0 :(得分:0)

我使用教程https://medium.com/@ahsan.ayaz/how-to-handle-cors-in-an-angular2-and-node-express-applications-eb3de412abef

解决了这个问题

只缺少细节......旁边的线条 从'@ angular / http'导入{BrowserXhr}; 和 从'./app/path-to-file/cust-ext-browser-xhr'导入{CustExtBrowserXhr}; 你应该补充一下 从'@ angular / common'导入{LocationStrategy,HashLocationStrategy};