4

My node.js server is using express-session for authentication.

const express = require('express')
const session = require('express-session')

const app = express()

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://192.168.1.24:3000");
    res.header("Access-Control-Allow-Credentials", 'true')
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
})

app.use(session({ secret: 'neverGotWhatShouldBeHere', resave: false, saveUninitialized: false }))

app.get('/login', (req, res) => {
    req.session.userAuth = "some data"
    req.session.cookie.maxAge = 10 * 1000
    res.send({ prob: 'no' })
})

app.get('/restricted', (req, res) => {
    if (req.session.userAuth == "some data")
        res.send({ prob: 'no', data: 'top secret confidential data' })
    else
        res.send({ prob: 'log in to see data' })
})

app.listen(3000, () => console.log(`Example app listening at http://localhost:3000`))

When I access it from the browser, all works well. I can see the cookie and it disappears 10 seconds later, forcing me to log in again.

Then I created a React application using create-react-app.

App.js:

import React, { Component } from 'react';
import './App.css';

class App extends Component {

  remoteLogin = () => {
    fetch('http://192.168.1.25/login', { credentials: 'include' }).then((response) => {
      return response.json().then((jsonResponse) => {
        console.log(jsonResponse)
      }).catch((err) => {
        console.log("Error: " + err)
      })
    })
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.remoteLogin} >Log in</button>
      </div>
    )
  }
}

export default App;

When I click the button, I see the json data from the server, but I get no cookie.

How can I get the cookie in the React application?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Matan Livne
  • 173
  • 3
  • 6

2 Answers2

1

Dont know if it help you, but i use react-cookie for my session cookies :

https://www.npmjs.com/package/react-cookies

You just save your cookie with all the data you want,only with react

Jonathan Delean
  • 1,011
  • 1
  • 8
  • 25
  • How does this work with the express backend? The link you gave doesn't seem to have any examples of the backend to go with it – Raphael Morgan Nov 27 '21 at 20:34
1

Try using cors module and set the origin to frontend and option withCredentials: true. For me it worked.