inSession variable in express: set to false

i keep receiving

inSession:false

https://i.sstatic.net/4IW0f.png

when attempting to log in, it is expected to return true.

I am utilizing express session, in combination with postges and sequalize.

I have logged the state values and they are being rendered correctly, so they are not undefined.

A more detailed error

Proxy error: Could not proxy request /api from localhost:3000 to http://localhost:5000/ (ECONNREFUSED).

routes/users.js (manages the login process)

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 Manages the Front End.

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;

server ...

     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 (frontend 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));
  }

  ...

Answer №1

Have you attempted logging in sessionChecker on the server? It seems like there may be an undefined variable causing issues. If it were me, I would have tackled it like this:

// 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)});
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A notification appears when the record is being inserted after clicking the button

Just venturing into the PHP and MYSQL realm, so please excuse any beginner questions. Before I submit data from a form to my SQL table, I'd like to display a confirmation POP UP message asking "Are you sure you want to insert this data?" ...

Using dynamic template URLs in resolving with Angular's UI-Router can provide flexibility

Currently, I have implemented a parent directive for an entire view to interchange templates based on the outcome of a promise. .directive('myDirective', function(myService) { var rootDir = '/path/to/templates'; return { ...

Creating a Drop-Down Button Using HTML, CSS, and JavaScript

I am currently working with the following code: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=PT+Sans ...

What is the best way to remove excess content that falls outside the viewBox?

Is there a function or method to trim a path that extends beyond the viewbox rather than simply concealing it? I am currently using svg-edit, which has a specific viewbox or canvas area. Any elements drawn outside of this canvas remain hidden. However, wh ...

How to redefine TypeScript module export definitions

I recently installed a plugin that comes with type definitions. declare module 'autobind-decorator' { const autobind: ClassDecorator & MethodDecorator; export default autobind; } However, I realized that the type definition was incorrec ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

D3.js: Unveiling the Extraordinary Tales

I'm currently working on a project that requires me to develop a unique legend featuring two text values. While I have successfully created a legend and other components, I am facing difficulties in achieving the desired design. Specifically, the cur ...

Utilize the function expression located in an external module

Is there a way to access and call the function expression "extractUserProgress" from an external module in server.js? UPDATE Upon further examination of my code, I have found that there is a series of nested function expressions following the "extractUser ...

Struggling to map JSON data (received from WCFRest) onto an HTML table

After creating a WCFRestful service that populates data in JSON format as shown below: {"GetEmployeesJSONResult":"[{\"Name\":\"Sumanth\",\"Id\":101,\"Salary\":5000},{\"Name\":\"Sumanth\",\"I ...

Avoid having to refresh the page on create-react-app after uploading an image or file

Currently, my application is set up with 'create-react-app' and I am retrieving images from a folder within the 'src' directory. However, when a new image is uploaded through a form submission, it causes the page to reload as the image ...

Generate a Table Using JSON Data with AngularJS and ng-repeat

I have some JSON data that looks like this: { "Workout1": { "Name": "First", "Rounds": [ { "Exercises": [ { "Name": "Exercise1", "Repeat": 10 }, { "Name": "Exercise2 ...

Having trouble viewing a dynamically adjusting Angular NVD3 graph embedded in bootstrap

I have been utilizing the NVD3 library along with bootstrap 3.0 for my project. I have two divs with the classes "col-md-6 col-sm-12" positioned side by side. My goal is to showcase charts in both of these divs. To ensure that the charts are displayed corr ...

Avoiding the default action to submit AJAX form data won't result in any changes to the front end?

Currently, I am working with Flask and have utilized JavaScript to prevent default behavior in order to send all the necessary data through an AJAX request. However, I am facing an issue where although my view contains all the data (verified by console out ...

Having issues with jQuery's .text() method not functioning as expected on XML elements

Looking at the javascript code below: function getAdminMessageFromXML(xml) { alert('xml: ' + xml); alert("Text of admin message: " + $(xml).find('dataModelResponse').find('adminMessage').text()); return $(xml).fin ...

Is it possible to have a hidden div box within a WordPress post that is only visible to the author of the

How can I create a div box with "id=secret" inside a post that is only visible to the author of the post? I initially made it for the admin, but now I want the id to be visible exclusively to the post's author. For instance: If the author is curren ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

Renaming errors within a project with a complex nested structure using npm

I am encountering an issue in my NodeJS project which consists of nested subprojects with their own package.json files. Whenever I make changes to dependencies in the subprojects, I encounter errors similar to the one below: npm ERR! code ENOENT npm ERR! ...

Analyzing JSON information using an AJAX request from a local file

I have a PHP file on a web server that is executing queries to a MySQL database. Currently, I am testing a site on my local PC which utilizes a JS file with AJAX requests to retrieve JSON data from the mentioned PHP file. My question is whether it is fea ...

Set a maximum limit for the number of checkboxes that can be selected

If there are 10 checkboxes on a page, I am searching for a specific behavior: Use a variable called maxSelections to control the maximum number of selectable checkboxes Once maxSelections is reached, disable the other checkboxes on the page Even after re ...

The element is not positioned correctly due to the absolute positioning

This is my first attempt at creating a jQuery plugin and I have almost got it working correctly. You can view the example here. I've been struggling for days to position an element as desired. The goal is to display some text with an optional downwar ...