在发布请求后反应渲染响应页面

时间:2018-12-22 18:40:23

标签: javascript node.js reactjs

我有一个名为“登录”的React组件。

成功获得登录凭据后,后端将重定向到用户页面。

  app.post(
    "/Login",
    passport.authenticate("local", {
      failureRedirect: "/login",
      failureFlash: true
    }),
    function(req, res) {
      res.redirect("/User");
    }
  );

尽管没有更改,但在浏览器页面中。这是网络统计信息的图片:

enter image description here

在图片上,您可以看到第二个对/User的请求,但是浏览器没有加载新页面。

这是Login组件:

import React, { Component } from "react";
import { Redirect } from "react-router-dom";
import NavBar from "../components/styled/NavBar";
import { UserInput, Label, SubmitButt } from "../components/styled/Forms";
import styled from "styled-components";

const FormWrapper = styled.div`
  padding: 10px;
  border-radius: 5px;
  background-color: #f2f2f2;
`;
const Form = styled.form``;

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: ""
    };
  }

  submitForm = async e => {
    e.preventDefault();
    const res = await fetch("/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        username: this.state.username,
        password: this.state.password
      })
    });
  };

  onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  render() {
    return (
      <React.Fragment>
        <NavBar /> <h1>Hello from Login {this.props.location.msg}</h1>
        <FormWrapper>
          <Form>
            <Label>Username</Label>
            <UserInput
              name="username"
              type="text"
              placeholder="Type your username here"
              value={this.state.name}
              onChange={this.onChange}
            />
            <Label>Password</Label>
            <UserInput
              name="password"
              type="password"
              placeholder="Type your password here"
              value={this.state.name}
              onChange={this.onChange}
            />
            <SubmitButt onClick={this.submitForm}>Submasdasdit</SubmitButt>
          </Form>
        </FormWrapper>
      </React.Fragment>
    );
  }
}

export default Login;

0 个答案:

没有答案