javascript - Express Session 属性区分浏览器和 Postman

标签 javascript node.js angular express-session

更新

我认为值得一提的是,我正在运行在端口 4200 上运行的 Angular CLI,而我的服务器在端口 8080 上运行。这可能是个问题吗?这是我目前唯一能想到的事情

当我调用路由“/auth/login”时,我在 session 对象上设置了一个登录属性。要检查用户是否已通过身份验证,请向“/auth/checktoken”发出请求。在这里,我检查 req.session 对象上是否存在 loggedIn 属性。当我在 Postman 中执行这些请求时,一切正常,但在使用浏览器时,我的 session.loggedIn 属性未定义。我将在下面粘贴相关代码。在此先感谢您的帮助

服务器端

router.get('/checktoken', (req, res) => {
  if(!req.session.loggedIn) {
    return res.status(401).send({
      userTitle: 'Not authorised',
      userMessage: 'You are not authorised to view this'
    })
  }

  return res.status(200).send()
})

客户端

@Injectable()
export class CheckAuthenticationService implements CanActivate {
  constructor(
    private router: Router,
    private http: HttpClient) { }

  canActivate() {
    this.http.get('http://localhost:8080/auth/checktoken', { responseType: 'text' })
      .toPromise()
      .then(() => {
        this.router.navigate(['admin']);
      })
      .catch( () => {
        this.router.navigate(['login']);
      });

    return true;
  }
}

设置 loggedIn 属性的登录代码片段

if (user) {
  user.comparePassword(password, (err, isMatch) => {
    if (isMatch && isMatch) {
      req.session.loggedIn = user;
      res.status(200).send()
    } else {
      res.status(404).send({
        userTitle: 'Wrong password',
        userMessage: 'Please make sure your password is correct'
      });
      }
    });
  }

session 存储设置

app.use(session({
  name: 'jack-thomson',
  secret: SECRET_KEY,
  saveUninitialized: false,
  resave: true,
  store: new MongoStore({
    mongooseConnection: mongoose.connection
  })
}))

这一切在 Postman 中都有效,但是当在客户端访问这些端点时,.loggedIn 总是未定义

最佳答案

我之前遇到过同样的问题。我认为这是关于cors凭证的。我在 React 上使用 Axios 将 POST 数据登录到我的 Express 后端应用程序。我需要添加这些行:

    import axios from 'axios';
    axios.defaults.withCredentials = true;

然后在我的 Express 项目中,我添加了 cors:

var cors = require('cors');
app.use(cors({
  credentials: true, 
  origin: 'http://localhost:3000'  // it's my React host
  })
);

最后我可以像往常一样调用我的登录函数,例如:

signup(){
    var url = 'http://localhost:3210/'
    axios.post(url, {
      email: this.refs.email.value,
      username: this.refs.username.value,
      password: this.refs.password.value,
      passwordConf: this.refs.passwordConf.value
    })
    .then((x)=>{
      console.log(x);
      if(x.data.username){
        this.setState({statusSignup: `Welcome ${x.data.username}`});
      } else {
        this.setState({statusSignup: x.data});
      }
    })
    .catch((error)=>{console.log(error)})
  }

  login(){
    var url = 'http://localhost:3210/';
    var data = {
      logemail: this.refs.logemail.value,
      logpassword: this.refs.logpassword.value,
    };
    axios.post(url, data)
    .then((x)=>{
      console.log(x);
      if(x.data.username){
        this.setState({statusLogin: `Welcome ${x.data.username}`});
      } else {
        this.setState({statusLogin: x.data});
      }
    })
    .catch((error)=>{console.log(error)})
  }

而且有效!希望这能解决您的问题。

关于javascript - Express Session 属性区分浏览器和 Postman,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46753362/

相关文章:

javascript - 如何测试 NaN?

javascript - 当在对象中指定自定义键时,它会将其转换为数字

javascript - 从机器人发送的随机报价 - 意外的标识符

node.js - 如何从脚本命令访问 process.env 变量

javascript - jQuery(this) 和 qtip 不工作

node.js - 需要JS : Missing file gives error for first time but results in request timeout for further requests until server is restarted

java - 将node.js文件打包到fatJar中

Visual Studio Code 中 HTML 组件中的 Angular 10 “No definition found for …”

javascript - 如何在 Angular 中嵌套 routerLink

javascript - 将 XML 解析为 Javascript 对象