我发出请求时,React不保留会话数据

时间:2019-12-31 06:12:51

标签: node.js reactjs express session redux

反应似乎困扰了我的会议?通过提取进行请求时,会话数据没有保存,结果是:

Session {
  cookie:
   { path: '/',
     _expires: 2019-12-31T07:36:13.407Z,
     originalMaxAge: 7200000,
     httpOnly: true,
     sameSite: true,
     secure: false },
  user: { userId: '5ddc90090b5f01596e1450f4', username: 'Test' } }
::1 - - [Tue, 31 Dec 2019 05:36:13 GMT] "POST /api/session HTTP/1.1" 200 55 "http://localhost:3000/login" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
Session {
  cookie:
   { path: '/',
     _expires: 2019-12-31T07:36:19.514Z,
     originalMaxAge: 7200000,
     httpOnly: true,
     sameSite: true,
     secure: false } }
::1 - - [Tue, 31 Dec 2019 05:36:19 GMT] "GET /api/session HTTP/1.1" 200 2 "http://localhost:3000/dashboard" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"

当我失眠时,一切都很好:

Session {
  cookie:
   { path: '/',
     _expires: 2019-12-31T06:05:02.241Z,
     originalMaxAge: 7200000,
     httpOnly: true,
     secure: false,
     sameSite: true },
  user: { userId: '5ddc90090b5f01596e1450f4', username: 'Test' } }
::ffff:127.0.0.1 - - [Tue, 31 Dec 2019 05:40:21 GMT] "POST /api/session HTTP/1.1" 200 55 "-" "insomnia/7.0.5"
Session {
  cookie:
   { path: '/',
     _expires: 2019-12-31T06:05:02.241Z,
     originalMaxAge: 7200000,
     httpOnly: true,
     secure: false,
     sameSite: true },
  user: { userId: '5ddc90090b5f01596e1450f4', username: 'Test' } }
::ffff:127.0.0.1 - - [Tue, 31 Dec 2019 05:40:23 GMT] "GET /api/session HTTP/1.1" 200 64 "-" "insomnia/7.0.5"

看看user如何在会话数据中保留?我不知道为什么在React的请求中没有发生这种情况。

这是我在React中的登录页面(触发POST请求)

import React from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { login } from "../actions/session";

const Login = ({ errors, login }) => {
  const handleSubmit = e => {
    e.preventDefault();
    const user = {
      email: e.target[0].value,
      password: e.target[1].value,
    };
    login(user);
  }  

  return (
    <>
      <h1>Login</h1>
      <p>{errors}</p>
      <form onSubmit={handleSubmit}>
        <label>
          Email:
          <input type="email" name="email" />
        </label>
        <label>
          Password:
          <input type="password" name="password" />
        </label>
        <input type="submit" value="Submit" />
      </form>
      <Link to="/signup">Signup</Link>
    </>
  );
};

const mapStateToProps = ({ errors }) => ({
  errors
});

const mapDispatchToProps = dispatch => ({
  login: user => dispatch(login(user))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Login);

这是要分派的动作:

export const login = user => async dispatch => {
  const response = await apiUtil.login(user);
  const data = await response.json();

  if (response.ok) {
    return dispatch(recieveCurrentUser(data));
  }

  return dispatch(receiveErrors(data));
}

这就是我发出请求的方式

export const login = user => (
  fetch("http://localhost:8080/api/session", {
    method: "POST",
    body: JSON.stringify(user),
    headers: {
      "Content-Type": "application/json"
    }
  })
);

这是我要在其中获取数据的仪表板

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { logout, getUser } from '../actions/session';
import { getTransactions } from '../actions/transactions';

const uuid = require('uuid/v4');

class Dashboard extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    // this.props.getTransactions();
  };

  handleSubmit = () => {
    console.log("here");

    this.props.getUser();
  }

  render() {
    return (
      <div className="container">
        <h1>Hi {this.props.session.username}</h1>
        <p>You are now logged in!</p>
          {
            <div className="transactions">
            this.props.transactions.forEach(element => (
              <h1>element.title</h1>
              <p>element.uuid ? element.uuid : uuid()</p>
            ));
            </div>
          }
        <button onClick={this.props.logout}>Logout</button>
        <button onClick={this.handleSubmit}>Get Session Data</button>
        <p>{ this.props.session.username }</p>
      </div>
    );
  };
};

const mapStateToProps = ({ session, transactions }) => ({
  session,
  transactions
});

const mapDispatchToProps = dispatch => ({
  logout: () => dispatch(logout()),
  getUser: () => dispatch(getUser())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Dashboard);

这是我发送的请求,用于执行获取会话数据(在按钮中)的GET请求:

export const getData = () => (
  fetch("http://localhost:8080/api/session")
);

这是我要开的动作:

export const getUser = () => async dispatch => {
  const response = await apiUtil.getData();
  const data = await response.json();

  if (response.ok) {
    return dispatch(recieveCurrentUser(data));
  }
}

2 个答案:

答案 0 :(得分:0)

我假设当您指的是Insomnia时,您正在谈论HTTP调试器,并且您也在某种类型的React开发服务器(例如Webpack)上运行前端代码,如果这样的话,很可能意味着您的开发服务器是与后端托管在不同的服务器上(在此情况下,不同的端口表示不同的服务器)。由于Insomnia不是浏览器,因此没有很多限制,其中之一是它允许向几乎任何服务器发出请求并自由读取响应,而对于浏览器而言,情况并非如此,以使读取响应变得“复杂” '请求您需要传递一些其他标题。

您可以阅读有关如何获取here的信息

关于标题本身和场景here

希望您的服务器配置为接受并响应COR,否则您将不得不进行必要的更改。

答案 1 :(得分:0)

尝试在您的credentials中加入fetch

export const login = user => (
  fetch("http://localhost:8080/api/session", {
    method: "POST",
    body: JSON.stringify(user),
    headers: {
      "Content-Type": "application/json"
    },
    credentials: 'include'
  })

);