【问题标题】:Extracting React API calls to Express backend server将 React API 调用提取到 Express 后端服务器
【发布时间】: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


    【解决方案1】:

    对于任何想知道的人来说,简单的答案是:

    A.) 是的,将 React 应用程序放在 /client 子文件夹中

    B.) 将以下内容添加到 client 的 package.json:

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

    我没有构建并推送到生产环境,所以我还不知道 C.) 的答案。

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 2019-05-30
      • 2017-08-30
      • 2020-03-15
      • 2021-05-09
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多