我如何让我的快递服务器从我的React客户端应用程序获取请求?

时间:2018-12-02 08:01:14

标签: javascript reactjs express

我正在开发我的第一个Express后端React前端应用程序。当前正在用户注册/登录/注销部分。

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const keys = require('./config/keys')
const passport = require('passport');
const session = require('express-session');
const LocalStrategy = require('passport-local');
// const passportLocalMongoose = require('passport-local-mongoose');
const User = require('./models/User');

const app = express();

// Use BodyParser
app.use(bodyParser.urlencoded({ extended: true }));

// Passport
app.use(passport.initialize());
app.use(passport.session());

app.use(session({
  secret: 'Rusty is the best',
  saveUninitialized: false,
  resave: false
}));

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// Connect to the Database
const db = keys.mongoURI
mongoose
  .connect(db, { useNewUrlParser: true })
  .then(() => console.log(`MongoDB connected...`))
  .catch(err => console.log(err));

// Routes
const items = require('./routes/api/items')
app.use('/api/items', items);

// Auth Routes
app.post('/register', function(req, res) {
  User.register(new User({ username: req.body.username }), req.body.password, function(err, user) {
    if (err) {
      console.log(err);
      return res.render('/register');
    }
    passport.authenticate('local')(req, res, function() {
      res.redirect('/secret');
    })
  })
});

app.post('/login', passport.authenticate('local', {
    successRedirect: '/secret',
    failureRedirect: '/login'
  }), function(req, res) {
});

app.get('/logout', function(req, res) {
  req.logout();
  res.redirect('/');
})

// Port and Listen
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on ${port}...`));

我的express server.js文件末尾的发布路线工作正常,但是当我进入app.get('/ logout')时遇到问题。 我的服务器在5000上运行,客户端在3000上运行。 我的客户端project.json中有“ proxy”:“ suggestion of Ingo Bürk”。 localhost:3000 / logout返回一个空白页面,而localhost:5000 / logout返回res.send消息“您已点击退出页面”。

有人知道我该如何解决吗?

编辑:这是我的反应路由器,以显示客户端如何路由

import React, { Component } from 'react';
import { Route, BrowserRouter } from 'react-router-dom';

import Input from './components/Input';
import SignUp from './components/SignUp';
import Form from './components/Form';
import LogIn from './components/LogIn';
import SignUp2 from './components/SignUp2';
import Profile from './components/Profile';
import Home from './components/Home';
import LogOut from './components/LogOut';


class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          <Route exact path='/' component={ Home } />
          <Route path='/register' component={ SignUp2 } />
          <Route path='/changeThisBackToRegister' component={ SignUp } />
          <Route path='/form' component={ Form } />
          <Route path='/login' component= { LogIn } />
          <Route path='/profile' component = { Profile } />
          <Route path='/secret' component = { Input } />
          <Route path='/logout' component = { LogOut } />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

更改您的/logout api响应以发送json响应。

app.get('/logout', function(req, res) {
  req.logout();
  res.json({success: true});
})

在您的Logout组件中,安装组件时进行/logout调用。

import React, { Component } from 'react';

export default class Logout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      logoutSuccess: false
    };

  }
  componentDidMount() {
    fetch('/logout')
    .then((response) => response.json())
    .then(() => {
      this.setState({logoutSuccess: true});
    });
  }
  render() {
    const { logoutSuccess } = this.state;
    return (
      <div>
        { logoutSuccess && (<div>Logout Success</div>)}
      </div>
    );
  }
}