React - Node.js uygulamasında locals ile session verisi taşıma

bastila

Hectopat
Katılım
28 Kasım 2019
Mesajlar
707
Makaleler
1
Çözümler
7
React tarafından sunucuya istek gönderip kullanıcı giriş yaptıktan sonra req. Session. Auth bilgisini true olarak yapıp res. Locals. Auth aracılığı ile sunucu tarafında her yerde bu bilgiyi tutmak ve kullanmak istiyorum. Ayrıca session endpointi ile React tarafına istediğimde almak istiyorum bu bilgiyi. Kodu çok basite indirgedim rahat anlaşılması için.

React tarafı:

JavaScript:
import axios from 'axios'
import { useState } from 'react'

function App() {

  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const data = {
    email: email,
    password: password
  }
  const requestHandler = async (e) => {
    e.preventDefault()
    if (data.email && data.password) {
      const response = await axios.post("http://localhost:5000/login", data)
      console.log(response.data)
      const auth = await axios.get("http://localhost:5000/")
      console.log(auth)
    }
  }

  return (
    <div className="App">
      <form action="">
        <label htmlFor="">email</label>
        <input type="text" onChange={(e) => { setEmail(e.target.value) }} />
        <label htmlFor="">password</label>
        <input type="password" onChange={(e) => { setPassword(e.target.value) }} />
        <button type='submit' onClick={requestHandler}>REQUEST</button>
      </form>
    </div>
  );
}

export default App;


Node.js tarafı:
JavaScript:
const express = require("express")
const app = express()
const cors = require("cors")
const bodyParser = require("body-parser")
const session = require("express-session")

app.use(session({
    secret: "secret key",
    resave: false,
    saveUninitialized: false
}))


app.use(cors())
app.use(bodyParser.json())

app.use(function (req, res, next) {
    res.locals.auth = req.session.auth
    next()
})

app.get("/", (req, res) => {
    res.send({ session: res.locals.auth })
    console.log("locals", res.locals)
})


app.post("/login", (req, res) => {
    const { email, password } = req.body
    if (email && password) {
        req.session.auth = true
    }
    console.log(email)
    console.log(password)
})

app.listen(5000, () => {
    console.log("Sunucu 5000 portunda çalışıyor.")
})


Problem şu;
Kod:
app.use(function (req, res, next) {
 res.locals.auth = req.session.auth
 next()
})
Bu aşamada sessiondan bilgi gelmiyor auth bilgisi undefined tanımlanıyor. Aslında salt nodejs ile bu işlemleri yapmıştım daha önce ama react ile entegre edemedim.
Eksik olan, benim göremediğim ya da yanlış yaptığım bir şey mi var?
 

Geri
Yukarı