You'll need to 1. implement express cors, and 2. add a proxy from react to your server
[1] https://expressjs.com/en/resources/middleware/cors.html
npm install cors
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
[2] https://create-react-app.dev/docs/proxying-api-requests-in-development/
In your react's package.json
, add
"proxy": "http://localhost:5000",
Note that this will work in development only.
For production, you'll need to serve the client from the server.
See https://create-react-app.dev/docs/deployment
const express = require('express');
const cors = require('cors')
const path = require('path');
const app = express();
app.use(cors());
/**
* add your API routes here to avoid them getting overtaken
* by the statically served client
*/
/**
* add this as the last handler
*/
if (process.env.NODE_ENV === "production") {
const pathToClientBuild = path.join(__dirname, '..', 'path', 'to', 'client', 'build');
app.use(express.static(pathToClientBuild));
/**
* experiment with '/' and '/*' and see what works best for you
*/
app.get('/*', function (req, res) {
res.sendFile(path.join(pathToClientBuild, 'index.html'));
});
}
app.listen(5000);
(and to make it work, you'll need to build the client first, and then serve the server with NODE_ENV=production node ./server.js
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…