创建React App + Express 后台的应用

前端之家收集整理的这篇文章主要介绍了创建React App + Express 后台的应用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

创建express app

  • 全局安装 express-generator

  1. $ npm install -g express-generator
  • 创建express app

  1. $ express react-backend
  • 安装依赖包

  1. $ npm install
  • 修改react-backend/routes/users.js,返回简单的数据,方便测试

  1. var express = require('express');
  2. var router = express.Router();
  3.  
  4. /* GET users listing. */
  5. router.get('/',function(req,res,next) {
  6. // Comment out this line:
  7. //res.send('respond with a resource');
  8.  
  9. // And insert something like this instead:
  10. res.json([{
  11. id: 1,username: "samsepi0l"
  12. },{
  13. id: 2,username: "D0loresH4ze"
  14. }]);
  15. });
  16.  
  17. module.exports = router;
  • 启动express app

  1. $ PORT=3001 node bin/www

把端口设置成3001的原因是因为react app 会使用3000端口,避免冲突

创建react app

  • 全局安装 create-react-app

  1. $ npm install -g create-react-app
  • 在react-backend文件夹下创建react app(也可以在其他文件夹下)

  1. # 在这里安装的时候 真心很慢,回头我研究一下,改成自己创建react应用,应该会快一点
  2. $ create-react-app client
  • 设置proxy

  1. $ cd client
  2. $ vim package.json
  3.  
  4. # 代码
  5. "scripts": {
  6. "start": "react-scripts start","build": "react-scripts build","test": "react-scripts test --env=jsdom","eject": "react-scripts eject"
  7. },"proxy": "http://localhost:3001"

proxy 是你后台服务器的地址

  1. import React,{ Component } from 'react';
  2. import './App.css';
  3.  
  4. class App extends Component {
  5. state = {users: []}
  6.  
  7. componentDidMount() {
  8. fetch('/users')
  9. .then(res => res.json())
  10. .then(users => this.setState({ users }));
  11. }
  12.  
  13. render() {
  14. return (
  15. <div className="App">
  16. <h1>Users</h1>
  17. {this.state.users.map(user =>
  18. <div key={user.id}>{user.username}</div>
  19. )}
  20. </div>
  21. );
  22. }
  23. }
  24.  
  25. export default App;
  • 启动应用

  1. $ npm start

在浏览器上访问localhost:3000,就能看到传递过来的用户列表了。

参考链接https://daveceddia.com/create...

猜你在找的React相关文章