【问题标题】:express session inSession: false表达会话 inSession: false
【发布时间】:2019-01-30 00:19:52
【问题描述】:

我一直在努力

inSession:假

登录时应该返回true。

我正在使用express session,以及postges,sequalize。

我 console.log 记录状态值并呈现值,因此它不是未定义的。

更深层次的错误

代理错误:无法将请求 /api 从 localhost:3000 代理到 http://localhost:5000/ (ECONNREFUSED)。

routes/users.js(处理登录逻辑)

router.post('/login', function(req, res, next) {
  const email = req.body.email;
  const password = req.body.password;
  User.findOne({
    where: {email: email}

  }).then( user => {

    if(!user){
      res.status(200).send({ incorrectEmail: true, inSession: false, msg: "Incorrect Email" })
    }else if(!user.validPassword(password)){
      res.status(200).send({ incorrectPassword: true, inSession: false, msg: "Incorrect Password" })
    }else{
      res.status(200).send({
        inSession: true, msg: "Logged in!", loggedEmail: user.email
      })
    }

  }).catch(err => next(err))
});

signIn.js 处理前端。

import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import axios from 'axios';
class signIn extends Component{

    constructor(props){
        super(props)

        this.state = {
            email:"",
            password: "", 
            loggedEmail:"",
            loginError: "",    
            userLoggedIn: false,
            emailBlank: true,
            passwordBlank: true,
            emailInvalid: false,
            passwordInValid: false,
        }

        this.handleChange = this.handleChange.bind(this);

    }

    handleChange = (e) =>{
        e.preventDefault();

        this.setState({
            [e.target.name]: e.target.value
        });

    }


    handleSubmit = () => {

        this.setState({
            email: this.state.email, 
            password: this.state.password


        });

        if (!this.state.emailBlank && !this.state.passwordBlank){
            axios.post('/api/users/login',{
                email: this.state.email, 
                password: this.state.password


            }).then ( res => { 
                if (res.data.incorrectEmail|| res.data.incorrectPassword ){
                    this.setState({ loginError: res.data.msg})
                }
                this.setState({ userLoggedIn: res.data.inSession, loggedEmail: res.data.loggedEmail})

            }).catch( err => console.log(err))

        }else{
            this.setState({ emailInvalid: true, passwordInValid: true})

            console.log(  this.state.emailInvalid, this.state.passwordInValid)
        }

    }

    render(){
        return (
            <div style={ {padding: '20px 100px'}}>
            <h1>Sign In</h1>
            <form onSubmit={this.handleSubmit}>      
                <TextField
                    id="outlined-name"
                    label="Email"
                    className=""
                    style={{width: 560}}
                    name="email"
                    value={this.state.email}
                    onChange={this.handleChange}
                    margin="normal"
                    variant="outlined"
                />  
                <br></br>
                <TextField
                    id="outlined-name"
                    label="Password"
                    name="password"
                    type="password"
                    style={{width: 560}}
                    className=""
                    value={this.state.password}
                    onChange={this.handleChange}
                    margin="normal"
                    variant="outlined"
                />  

                <br></br>

                <button type="submit"> Submit </button>

            </form>

            </div>

        );
    }





}

export default signIn;

服务器 ...

     app.use(session({
       key:'user_sid',
       secret: 'something',
       resave: false,
       saveUninitialized: false,
       cookie: {
       expires: 600000
      } 
     }))


    app.use((req, res, next) => {
      if (req.cookies.user_sid && !req.session.user){
        res.clearCookie('user_sid');
      }
      next();
    })

    sessionChecker = (req, res, next) => {
      if (req.session.user && req.cookies.user_sid){
        res.status(200).send({ inSession: true});
      } else {
        next();
      }
    }

    app.get('/api', sessionChecker, (req, res) => {
      res.status(200).send({ inSession: false });
    });

    app.use('/api/users', userRoute )

App.js(前端app.js)

class App extends Component {

  constructor(props){
    super(props);


    this.state = {
      inSession: false,
      loggedEmail: "",
    }

  }

  componentDidMount() {
    this.checkInSession()
  } 

  checkInSession = () => {
    axios.get('/api').then((res) => {
      this.setState({ inSession: res.data.inSession });
    }).catch(err => console.log(err));
  }

  ...

【问题讨论】:

    标签: javascript express


    【解决方案1】:

    您是否尝试过从服务器上的 sessionChecker 进行日志记录?看起来那里可能有一些未定义的东西。就我个人而言,我会执行以下操作:

    // sessionChecker = (req, res, next) => {
    //   if (req.session.user && req.cookies.user_sid){
    //     res.status(200).send({ inSession: true});
    //  } else {
    //    next();
    //  }
    // }
    
    app.get('/api', (req, res) => {
        res.status(200).send({ inSession: (req.session.user && req.cookies.user_sid)});
      }
    });
    

    【讨论】:

    • 让我试一试
    • 主要关心的是你究竟从 req.session.user 或 req.session.user_sid 中​​得到了什么......答案是服务器从这些变量中记录的内容。
    • 我从另一个 github 源复制了它,我不确定它到底是做什么的。我所知道的是,我需要一种方法让 react/node 知道用户已登录,并保持会话直到用户注销。上面的代码得到了 inSession:false 的影响。谢谢。
    • 我不太确定这个中间件是如何改变请求对象的,所以希望它会介入。有人可能会更改传入的请求以从服务器获得他们想要的响应。为了安全起见,我会花一些时间阅读快速会话的文档。至少可以在每次调用之间记录整个请求以比较结果。或者,如果您完全禁用中间件,请查看 req.session.user 的外观。用户管理真的很烦人,我现在也在处理它。祝你好运。
    猜你喜欢
    • 2011-08-27
    • 2012-02-08
    • 1970-01-01
    • 2015-01-14
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多