如何将React添加到Express.js

时间:2017-07-17 11:43:23

标签: reactjs express react-router

我有快速生成器快递的基本文件。 现在我想添加对我的express文件夹的反应并整合与express的反应。我该怎么办?

1 个答案:

答案 0 :(得分:1)

在您的快递文件中,您需要将您的react文件夹链接为静态资源。

const express = require('express')
const path = require('path')

const app = express()

app.use(express.static(path.join(__dirname, 'client/build'))); // this is where your built react js files are

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname+'/client/build/index.html'));
}); // this makes sure that all paths access your react.js files

在开发过程中,您可以通过在package.json

中添加代理选项来访问您的快速应用

例如,当您使用

开始快递时
node index.js

当您指定另一个端口(如localhost:5000)时,它将在localhost:3000或其他地方提供服务

要访问您的快递应用程序发送的json或数据,您需要在客户端的 package.json中设置代理。代理用于访问数据,因此在客户端连接到本地主机之前,它会通过该代理访问正在发送的数据

例如,如果您的快速应用程序在localhost:5000上运行,请将以下内容添加到客户端package.json

"proxy": "http://localhost:5000"

首先启动您的快速应用程序然后启动您的反应应用程序,您将把您的反应应用程序与您的快速服务器结合起来。

相关问题