如何在客户端渲染的 React 应用程序中执行服务器端 API 请求?

问题描述 投票:0回答:1

我有一个 React 应用程序,我需要在其中执行涉及请求正文中的敏感凭据的 API 调用。我担心在服务器端渲染整个应用程序,有没有办法确保 API 调用在服务器端执行以防止敏感数据泄露?

我对SSR和CSR都有基本的了解,所以我不确定我想要的结果是否可以实现。具体来说,我不确定服务器端 API 调用是否需要服务器端渲染,尤其是在 React 18 中。

reactjs node.js server server-side-rendering react-dom
1个回答
0
投票

您可以在客户端渲染 (CSR) React 应用程序中执行服务器端 API 请求,而无需在服务器端渲染整个应用程序。

  1. 在您的服务器上设置代理 API 端点 使用环境变量来获取敏感信息
  2. 使用环境变量获取敏感信息
  3. 从 React 应用程序向后端 API 发出请求
  4. 处理回复

//React App code example

import React, { useState } from 'react';
import axios from 'axios';

function App() {
  const [data, setData] = useState(null);

  const fetchData = async () => {
    try {
      const response = await axios.post('/api/proxy', { your: "data" });
      setData(response.data);
    } catch (error) {
      console.error('There was an error!', error);
    }
  };

  return (
    <div>
      <button onClick={fetchData}>Fetch Data</button>
      {data && <div>{JSON.stringify(data)}</div>}
    </div>
  );
}

export default App;

//An example with node.js 

require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.json());

app.post('/api/proxy', async (req, res) => {
  try {
    const response = await axios.post('https://example.com/data', {
      data: req.body,
      headers: {
        'Authorization': `Bearer ${process.env.EXTERNAL_API_KEY}`
      }
    });
    res.json(response.data);
  } catch (error) {
    res.status(500).send(error.message);
  }
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

© www.soinside.com 2019 - 2024. All rights reserved.