如何使create-react-app与Node Back-end API一起使用
This is a very common question among newer React developers, and one question I had when I was starting out with React and Node.js. In this short example I will show you how to make create-react-app work with Node.js and Express Back-end.
這在新的React開發人員中是一個非常常見的問題,也是我剛開始使用React和Node.js時遇到的一個問題。 在這個簡短的示例中,我將向您展示如何使Node.js和Express Back-end可以使用create-react-app 。
創建React應用 (create-react-app)
Create a project using create-react-app.
使用create-react-app創建一個項目。
npx create-react-app example-create-react-app-expressCreate a /client directory under example-create-react-app-express directory and move all the React boilerplate code created by create-react-app to this new client directory.
在example-create-react-app-express目錄下創建一個/client目錄,并將所有由create-react-app的React樣板代碼移動到該新客戶端目錄。
cd example-create-react-app-expressmkdir client節點快速服務器 (The Node Express Server)
Create a package.json file inside the root directory (example-create-react-app-express) and copy the following contents:
在根目錄( example-create-react-app-express )內創建一個package.json文件,并復制以下內容:
{"name": "example-create-react-app-express","version": "1.0.0","scripts": {"client": "cd client && yarn start","server": "nodemon server.js","dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""},"dependencies": {"body-parser": "^1.18.3","express": "^4.16.4"},"devDependencies": {"concurrently": "^4.0.1"} }Notice I am using concurrently to run the React app and Server at the same time. The –kill-others-on-fail flag will kill other processes if one exits with a non zero status code.
注意我正在concurrently使用來concurrently運行React應用程序和Server。 如果一個以非零狀態碼退出,則–kill-others-on-fail標志將殺死其他進程。
Install nodemon globally and the server dependencies:
全局安裝nodemon和服務器依賴項:
npm i nodemon -g yarnCreate a server.js file and copy the following contents:
創建一個server.js文件并復制以下內容:
const express = require('express'); const bodyParser = require('body-parser');const app = express(); const port = process.env.PORT || 5000;app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));app.get('/api/hello', (req, res) => {res.send({ express: 'Hello From Express' }); });app.post('/api/world', (req, res) => {console.log(req.body);res.send(`I received your POST request. This is what you sent me: ${req.body.post}`,); });app.listen(port, () => console.log(`Listening on port ${port}`));This is a simple Express server that will run on port 5000 and have two API routes: GET - /api/hello, and POST -/api/world.
這是一個簡單的Express服務器,將在端口5000上運行,并具有兩個API路由: GET /api/hello和POST /api/world 。
At this point you can run the Express server with the following command (still inside the root directory):
此時,您可以使用以下命令運行Express服務器(仍在根目錄中):
node server.jsNow navigate to http://localhost:5000/api/hello, and you will get the following:
現在導航到http://localhost:5000/api/hello ,您將獲得以下信息:
We will test the POST route once we build the React app.
構建React應用后,我們將測試POST路由。
React App (The React App)
Now switch over to the client directory where our React app lives.
現在切換到我們的React應用程序所在的client目錄。
Add the following line to the package.json file created by create-react-app.
package.json下行添加到create-react-app的package.json文件中。
"proxy": "http://localhost:5000/"The key to using an Express back-end server with a project created with create-react-app is to use a proxy. This tells the Web-pack development server to proxy our API requests to our API server, given that our Express server is running on localhost:5000.
將Express后端服務器與通過create-react-app的項目一起使用的關鍵是使用代理。 假設我們的Express服務器在localhost:5000上運行,這將告訴Web-pack開發服務器將我們的API請求代理到我們的API服務器。
Now modify ./client/src/App.js to call our Express API Back-end, changes are in bold.
現在修改./client/src/App.js來調用我們的Express API后端,更改以粗體顯示。
import React, { Component } from 'react';import logo from './logo.svg';import './App.css';class App extends Component {state = {response: '',post: '',responseToPost: '',};componentDidMount() {this.callApi().then(res => this.setState({ response: res.express })).catch(err => console.log(err));}callApi = async () => {const response = await fetch('/api/hello');const body = await response.json();if (response.status !== 200) throw Error(body.message);return body;};handleSubmit = async e => {e.preventDefault();const response = await fetch('/api/world', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({ post: this.state.post }),});const body = await response.text();this.setState({ responseToPost: body });};render() {return (<div className="App"><header className="App-header"><img src={logo} className="App-logo" alt="logo" /><p>Edit <code>src/App.js</code> and save to reload.</p><aclassName="App-link"href="https://reactjs.org"target="_blank"rel="noopener noreferrer">Learn React</a></header><p>{this.state.response}</p><form onSubmit={this.handleSubmit}><p><strong>Post to Server:</strong></p><inputtype="text"value={this.state.post}onChange={e => this.setState({ post: e.target.value })}/><button type="submit">Submit</button></form><p>{this.state.responseToPost}</p></div>);} }export default App;We create callApi method to interact with our GET Express API route, then we call this method in componentDidMount and finally set the state to the API response, which will be Hello From Express.
我們創建callApi方法來與GET Express API路由進行交互,然后在componentDidMount調用此方法,最后將狀態設置為API響應,即“ Hello From Express” 。
Notice we didn’t use a fully qualified URL http://localhost:5000/api/hello to call our API, even though our React app runs on a different port (3000). This is because of the proxy line we added to the package.json file earlier.
請注意,即使我們的React應用程序在其他端口(3000)上運行,我們也沒有使用完全限定的URL http://localhost:5000/api/hello來調用我們的API。 這是因為proxy 我們之前添加到package.json文件中的行。
We have a form with a single input. When submitted calls handleSubmit, which in turn calls our POST Express API route then saves the response to state and displays a message to the user: I received your POST request. This is what you sent me: [message from input].
我們有一個帶有單個輸入的表單。 提交時,調用handleSubmit ,然后依次調用我們的POST Express API路由,然后將響應保存到狀態并向用戶顯示一條消息: 我收到了您的POST請求。 這是您發送給我的:[來自輸入的消息] 。
Now open ./client/src/App.css and modify .App-header class as follows (changes in bold)
現在打開./client/src/App.css并按如下所示修改.App-header類(更改為粗體)
.App-header { ...min-height: 50%; ...padding-bottom: 10px; }運行應用 (Running the App)
If you still have the server running, go ahead and stop it by pressing Ctrl+C in your terminal.
如果您仍在運行服務器,請在終端中按Ctrl + C停止它。
From the project root directory run the following:
從項目根目錄運行以下命令:
yarn devThis will launch the React app and run the server at the same time.
這將啟動React應用程序并同時運行服務器。
Now navigate to http://localhost:3000 and you will hit the React app displaying the message coming from our GET Express route. Nice ?!
現在導航到http://localhost:3000 ,您將點擊React應用,顯示來自我們GET Express路由的消息。 很好?!
Now, type something in the input field and submit the form, you will see the response from the POST Express route displayed right below the input field.
現在,在輸入字段中輸入內容并提交表單,您將看到輸入字段正下方顯示的POST Express路由的響應。
Finally take a look at at your terminal, you will see the message we sent from the client, that is because we call console.log on the request body in the POST Express route.
最后看看您的終端,您將看到我們從客戶端發送的消息,這是因為我們在POST Express路由的請求正文上調用console.log 。
生產部署到Heroku (Production Deployment to Heroku)
Open server.js and replace with the following contents:
打開server.js并替換為以下內容:
const express = require('express'); const bodyParser = require('body-parser'); const path = require('path');const app = express(); const port = process.env.PORT || 5000;app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));// API calls app.get('/api/hello', (req, res) => {res.send({ express: 'Hello From Express' }); });app.post('/api/world', (req, res) => {console.log(req.body);res.send(`I received your POST request. This is what you sent me: ${req.body.post}`,); });if (process.env.NODE_ENV === 'production') {// Serve any static filesapp.use(express.static(path.join(__dirname, 'client/build')));// Handle React routing, return all requests to React appapp.get('*', function(req, res) {res.sendFile(path.join(__dirname, 'client/build', 'index.html'));}); }app.listen(port, () => console.log(`Listening on port ${port}`));Open ./package.json and add the following to the scripts entry
打開./package.json并將以下內容添加到scripts條目中
"start": "node server.js", "heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build"Heroku will run the start script by default and this will serve our app. Then we want to instruct Heroku to build our client app, we do so with heroku-postbuild script.
Heroku默認會運行start腳本,這將為我們的應用程序提供服務。 然后,我們要指示Heroku構建我們的客戶端應用程序,我們使用heroku-postbuild腳本來實現。
Now, head over to Heroku and log in (or open an account if you don’t have one).
現在,轉到Heroku并登錄(如果沒有,請開設一個帳戶)。
Create a new app and give it a name
創建一個新應用并命名
Click on the Deploy tab and follow the deploy instructions (which I think they are pretty self-explanatory, no point on replicating them here ?)
單擊“ 部署”選項卡,然后按照部署說明進行操作(我認為它們很不言自明,沒有必要在此處復制它們嗎?)
And that is it, you can open your app by clicking on the Open app button at the top right corner within the Heroku dashboard for your app.
就是這樣,您可以通過單擊Heroku儀表板右上角的“ 打開應用程序”按鈕來打開應用程序。
Visit the deployed app for this tutorial: https://cra-express.herokuapp.com/
請訪問已部署的應用程序以獲取本教程: https : //cra-express.herokuapp.com/
其他部署選項 (Other Deployment Options)
I write about other deployments options here:
我在這里寫有關其他部署選項的信息:
Netlify
Netlify
Now
現在
Heoku (more in-depth explanation)
Heoku (更深入的說明)
項目結構 (Project Structure)
This will be the final project structure.
這將是最終的項目結構。
Get the full code on the GitHub repository.
在GitHub存儲庫上獲取完整代碼。
Thank you for reading and I hope you enjoyed it. Any question, suggestions let me know in the comments below!
感謝您的閱讀,希望您喜歡它。 如有任何疑問,建議請在下面的評論中告訴我!
You can follow me on Twitter, GitHub, Medium, LinkedIn or all of them.
您可以在Twitter , GitHub , Medium , LinkedIn或所有它們上關注我。
This post was originally posted on my personal blog website.
該帖子最初發布在我的個人博客網站上 。
Update 8/25/19: I have been building a prayer web app called "My Quiet Time - A Prayer Journal". If you would like to stay in the loop please sign up through the following link: http://b.link/mqt ?
19年8月25日更新:我一直在構建一個禱告網絡應用程序,名為“ 我的安靜時間-禱告日記 ”。 如果您想停留在循環中,請通過以下鏈接進行注冊: http : //b.link/mqt
The app will be released before the end of the year, I have big plans for this app. To see some mockup screenshots follow the following link: http://pc.cd/Lpy7
該應用程序將在今年年底之前發布,我對此應用程序有很大的計劃。 要查看一些模型截圖,請點擊以下鏈接: http : //pc.cd/Lpy7
My DMs on Twitter are open if you have any questions regarding the app 😄
如果您對應用程序有任何疑問,我在Twitter上的 DM處于打開狀態😄
翻譯自: https://www.freecodecamp.org/news/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0/
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的如何使create-react-app与Node Back-end API一起使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到找袜子是什么意思
- 下一篇: node.js gbk编码_如何使用No