【发布时间】:2021-04-17 20:51:30
【问题描述】:
我有一个使用 Google API 获取日历数据的 React 站点。为了保密我的 API 密钥,我想提取对 Express 后端服务器的调用。该网站正在使用 react-router-dom,我想知道如何让它到达后端。
A.) 服务器应该在 React 应用程序的父文件夹中(并同时启动)还是无关紧要(只需使用 Express 正确设置路由)?
B.) 我如何从 React 应用程序之外到达后端以及 Express 路由的外观应该如何?
和
C.) 我已经看到了有关使用代理进行开发服务器调用的提示,但是对于生产构建,这会如何改变?
server.js 的当前状态:
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();
// Allow cross-origin
app.use(cors());
app.use(express.static('public'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
当前的 React App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import About from './components/About';
import Calendar from './components/Calendar';
import Home from './components/Home';
import Nav from './components/Nav';
import Footer from './components/Footer';
function App() {
return (
<div>
<Nav />
<Router>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/calendar" component={Calendar} />
</Router>
<Footer />
</div>
);
}
export default App;
还有 Calendar.js 页面组件:
import React, { useState, useEffect } from 'react';
import MonthCard from './MonthCard';
const Calendar = () => {
const [events, setEvents] = useState(null)
useEffect(() => {
// Make backend API call
// setEvents(apiResponse)
}, [])
return (
<div className="container text-center">
<div className="col-12">
<br />
<h1>Upcoming Shows</h1>
</div>
<div className="row justify-content-center">
<div className="col-6 text-center">
<p></p>
<h3>
Due to COVID-19 concerns, all shows are tentative and subject to
cancellation
</h3>
</div>
</div>
<br />
{events.map(arr => (
<MonthCard key={arr.month} month={arr.month} events={arr.shows} />
))}
</div>
);
};
export default Calendar;
【问题讨论】:
标签: node.js reactjs express react-router