日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

如何使create-react-app与Node Back-end API一起使用

發(fā)布時(shí)間:2023/11/29 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何使create-react-app与Node Back-end API一起使用 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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開發(fā)人員中是一個(gè)非常常見的問題,也是我剛開始使用React和Node.js時(shí)遇到的一個(gè)問題。 在這個(gè)簡(jiǎn)短的示例中,我將向您展示如何使Node.js和Express Back-end可以使用create-react-app 。

創(chuàng)建React應(yīng)用 (create-react-app)

Create a project using create-react-app.

使用create-react-app創(chuàng)建一個(gè)項(xiàng)目。

npx create-react-app example-create-react-app-express

Create 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目錄下創(chuàng)建一個(gè)/client目錄,并將所有由create-react-app的React樣板代碼移動(dòng)到該新客戶端目錄。

cd example-create-react-app-expressmkdir client

節(jié)點(diǎn)快速服務(wù)器 (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 )內(nèi)創(chuàng)建一個(gè)package.json文件,并復(fù)制以下內(nèi)容:

{"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運(yùn)行React應(yīng)用程序和Server。 如果一個(gè)以非零狀態(tài)碼退出,則–kill-others-on-fail標(biāo)志將殺死其他進(jìn)程。

Install nodemon globally and the server dependencies:

全局安裝nodemon和服務(wù)器依賴項(xiàng):

npm i nodemon -g yarn

Create a server.js file and copy the following contents:

創(chuàng)建一個(gè)server.js文件并復(fù)制以下內(nèi)容:

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.

這是一個(gè)簡(jiǎn)單的Express服務(wù)器,將在端口5000上運(yùn)行,并具有兩個(gè)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):

此時(shí),您可以使用以下命令運(yùn)行Express服務(wù)器(仍在根目錄中):

node server.js

Now navigate to http://localhost:5000/api/hello, and you will get the following:

現(xiàn)在導(dǎo)航到http://localhost:5000/api/hello ,您將獲得以下信息:

We will test the POST route once we build the React app.

構(gòu)建React應(yīng)用后,我們將測(cè)試POST路由。

React App (The React App)

Now switch over to the client directory where our React app lives.

現(xiàn)在切換到我們的React應(yīng)用程序所在的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后端服務(wù)器與通過create-react-app的項(xiàng)目一起使用的關(guān)鍵是使用代理。 假設(shè)我們的Express服務(wù)器在localhost:5000上運(yùn)行,這將告訴Web-pack開發(fā)服務(wù)器將我們的API請(qǐng)求代理到我們的API服務(wù)器。

Now modify ./client/src/App.js to call our Express API Back-end, changes are in bold.

現(xiàn)在修改./client/src/App.js來調(diào)用我們的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.

我們創(chuàng)建callApi方法來與GET Express API路由進(jìn)行交互,然后在componentDidMount調(diào)用此方法,最后將狀態(tài)設(shè)置為API響應(yīng),即“ 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.

請(qǐng)注意,即使我們的React應(yīng)用程序在其他端口(3000)上運(yùn)行,我們也沒有使用完全限定的URL http://localhost:5000/api/hello來調(diào)用我們的API。 這是因?yàn)?strong>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].

我們有一個(gè)帶有單個(gè)輸入的表單。 提交時(shí),調(diào)用handleSubmit ,然后依次調(diào)用我們的POST Express API路由,然后將響應(yīng)保存到狀態(tài)并向用戶顯示一條消息: 我收到了您的POST請(qǐng)求。 這是您發(fā)送給我的:[來自輸入的消息] 。

Now open ./client/src/App.css and modify .App-header class as follows (changes in bold)

現(xiàn)在打開./client/src/App.css并按如下所示修改.App-header類(更改為粗體)

.App-header { ...min-height: 50%; ...padding-bottom: 10px; }

運(yùn)行應(yīng)用 (Running the App)

If you still have the server running, go ahead and stop it by pressing Ctrl+C in your terminal.

如果您仍在運(yùn)行服務(wù)器,請(qǐng)?jiān)诮K端中按Ctrl + C停止它。

From the project root directory run the following:

從項(xiàng)目根目錄運(yùn)行以下命令:

yarn dev

This will launch the React app and run the server at the same time.

這將啟動(dòng)React應(yīng)用程序并同時(shí)運(yùn)行服務(wù)器。

Now navigate to http://localhost:3000 and you will hit the React app displaying the message coming from our GET Express route. Nice ?!

現(xiàn)在導(dǎo)航到http://localhost:3000 ,您將點(diǎn)擊React應(yīng)用,顯示來自我們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.

現(xiàn)在,在輸入字段中輸入內(nèi)容并提交表單,您將看到輸入字段正下方顯示的POST Express路由的響應(yīng)。

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.

最后看看您的終端,您將看到我們從客戶端發(fā)送的消息,這是因?yàn)槲覀冊(cè)赑OST Express路由的請(qǐng)求正文上調(diào)用console.log 。

生產(chǎn)部署到Heroku (Production Deployment to Heroku)

Open server.js and replace with the following contents:

打開server.js并替換為以下內(nèi)容:

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并將以下內(nèi)容添加到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默認(rèn)會(huì)運(yùn)行start腳本,這將為我們的應(yīng)用程序提供服務(wù)。 然后,我們要指示Heroku構(gòu)建我們的客戶端應(yīng)用程序,我們使用heroku-postbuild腳本來實(shí)現(xiàn)。

Now, head over to Heroku and log in (or open an account if you don’t have one).

現(xiàn)在,轉(zhuǎn)到Heroku并登錄(如果沒有,請(qǐng)開設(shè)一個(gè)帳戶)。

Create a new app and give it a name

創(chuàng)建一個(gè)新應(yīng)用并命名

Click on the Deploy tab and follow the deploy instructions (which I think they are pretty self-explanatory, no point on replicating them here ?)

單擊“ 部署”選項(xiàng)卡,然后按照部署說明進(jìn)行操作(我認(rèn)為它們很不言自明,沒有必要在此處復(fù)制它們嗎?)

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儀表板右上角的“ 打開應(yīng)用程序”按鈕來打開應(yīng)用程序。

Visit the deployed app for this tutorial: https://cra-express.herokuapp.com/

請(qǐng)?jiān)L問已部署的應(yīng)用程序以獲取本教程: https : //cra-express.herokuapp.com/

其他部署選項(xiàng) (Other Deployment Options)

I write about other deployments options here:

我在這里寫有關(guān)其他部署選項(xiàng)的信息:

  • Netlify

    Netlify

  • Now

    現(xiàn)在

  • Heoku (more in-depth explanation)

    Heoku (更深入的說明)

項(xiàng)目結(jié)構(gòu) (Project Structure)

This will be the final project structure.

這將是最終的項(xiàng)目結(jié)構(gòu)。

Get the full code on the GitHub repository.

在GitHub存儲(chǔ)庫(kù)上獲取完整代碼。

Thank you for reading and I hope you enjoyed it. Any question, suggestions let me know in the comments below!

感謝您的閱讀,希望您喜歡它。 如有任何疑問,建議請(qǐng)?jiān)谙旅娴脑u(píng)論中告訴我!

You can follow me on Twitter, GitHub, Medium, LinkedIn or all of them.

您可以在Twitter , GitHub , Medium , LinkedIn或所有它們上關(guān)注我。

This post was originally posted on my personal blog website.

該帖子最初發(fā)布在我的個(gè)人博客網(wǎng)站上 。



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日更新:我一直在構(gòu)建一個(gè)禱告網(wǎng)絡(luò)應(yīng)用程序,名為“ 我的安靜時(shí)間-禱告日記 ”。 如果您想停留在循環(huán)中,請(qǐng)通過以下鏈接進(jìn)行注冊(cè): 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

該應(yīng)用程序?qū)⒃诮衲昴甑字鞍l(fā)布,我對(duì)此應(yīng)用程序有很大的計(jì)劃。 要查看一些模型截圖,請(qǐng)點(diǎn)擊以下鏈接: http : //pc.cd/Lpy7

My DMs on Twitter are open if you have any questions regarding the app 😄

如果您對(duì)應(yīng)用程序有任何疑問,我在Twitter上的 DM處于打開狀態(tài)😄

翻譯自: https://www.freecodecamp.org/news/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0/

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的如何使create-react-app与Node Back-end API一起使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。