建立React App + Express 後臺的應用

建立express app

  • 全局安裝 express-generatorcss

$ npm install -g express-generator
  • 建立express appnode

$ express react-backend
  • 安裝依賴包react

$ npm install
  • 修改react-backend/routes/users.js, 返回簡單的數據,方便測試express

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
    // Comment out this line:
  //res.send('respond with a resource');

  // And insert something like this instead:
  res.json([{
      id: 1,
      username: "samsepi0l"
  }, {
      id: 2,
      username: "D0loresH4ze"
  }]);
});

module.exports = router;
  • 啓動express appnpm

$ PORT=3001 node bin/www

把端口設置成3001的緣由是由於react app 會使用3000端口,避免衝突json

建立react app

  • 全局安裝 create-react-appvim

$ npm install -g create-react-app
  • 在react-backend文件夾下建立react app(也能夠在其餘文件夾下)瀏覽器

# 在這裏安裝的時候  真心很慢,回頭我研究一下,改爲本身建立react應用,應該會快一點
$ create-react-app client
  • 設置proxy服務器

$ cd client
$ vim package.json

# 代碼
 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:3001"

proxy 是你後臺服務器的地址app

  • 修改client/src/App.js

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

class App extends Component {
  state = {users: []}

  componentDidMount() {
    fetch('/users')
      .then(res => res.json())
      .then(users => this.setState({ users }));
  }

  render() {
    return (
      <div className="App">
        <h1>Users</h1>
        {this.state.users.map(user =>
          <div key={user.id}>{user.username}</div>
        )}
      </div>
    );
  }
}

export default App;
  • 啓動應用

$ npm start

在瀏覽器上訪問localhost:3000,就能看到傳遞過來的用戶列表了。

參考連接:https://daveceddia.com/create...

相關文章
相關標籤/搜索