0

I am using Express for my Back end of my React app when i set a session in a page and redirect to another page of my web app the session deleted

Here my express code :

async function createUser(req, res, next) {
  try {
    let parameters = req.body
    let user = await models.User.create({
      displayName: parameters.displayName,
      phone: parameters.phone,
      sex: parameters.sex,
      password: parameters.password,
  })
  req.session.user = user.dataValues;
  res.json({
    status: 'success',
    user,
  })
}

and here is my react code :

onSubmit = (event) => {
  event.preventDefault()
  request.post('/newuser',{
    displayName:this.state.name,
    phone:this.state.phone,
    password:this.state.password,
    sex:this.state.sex
  })
  .then(function(response){
    this.props.authenticate(true)
    this.setState({
      auth:true
    })
  }.bind(this))
}

and here is my react render method:

render(){
  if(this.state.auth) 
    return <Redirect to='/profile' />;
}

with all this describes when i redirected to the profile page i dont have any session and all hope is gone :))

please help me solve this problem .

Mahdi
  • 1,355
  • 1
  • 12
  • 28
  • Possible duplicate of [Working with Sessions in Express.js](https://stackoverflow.com/questions/14218725/working-with-sessions-in-express-js) – ponury-kostek Oct 05 '18 at 09:22

1 Answers1

1

When you use axios for sending request you should do this :

In Front (React) : You should set withCredentials: true in axios setting like this :

import axios from 'axios'
import config from '../../config'

const request = axios.create({
  baseURL: config.url,
  timeout: 20000,
  withCredentials: true,
});

export default request

In Back (Node/Express) : you should add this code the the cors

const express = require('express')
const cors = require('cors')

app.use(cors({
  origin:['http://localhost:9520']//your front url,
  methods:['GET','POST'],
  credentials: true
}))

I figured it out by searching, Thanks for not helping though :))

Mahdi
  • 1,355
  • 1
  • 12
  • 28