如何在 AWS Amplify 上运行 React/Redux 应用程序的代理

2024-05-10

我最近实施了Proxy(在 Express.js 中)对于我的反应应用程序发出请求时隐藏 API URL。当我在本地主机上运行代理和应用程序时,它工作得非常好。现在我已准备好将我的应用程序部署到AWS 放大,我对如何让我的代理在那里运行有点困惑,因为我没有从 CLI 手动启动应用程序和代理。我需要使用EC2实例或者我可以使用以下方法实现此目的Amplify?

任何帮助将不胜感激!

这就是我的项目目录的样子:

这就是我的 Server.js 的样子:

const express = require('express'); 
const bodyParser = require('body-parser');
const app = express(); 
const axios = require('axios');
var cors = require('cors')
app.use(cors())
app.use(bodyParser.urlencoded({
    extended: false
 }));

const BASE_URL = 'https://my-aws-lambda-base-url/dev'
const port = process.env.PORT || 5000; 


app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept"
    );
    next();
  });

app.listen(port, () => console.log(`Listening on port ${port}`)); 

  app.use('/contact', require('body-parser').json(), async (req, res) => {
  
    
    try {
      
      await axios.post(`${BASE_URL}/contact`, {

              Email : req.body.Email,
              type :  req.body.type,
              Message : req.body.Message,
              Phone : req.body.Phone    
          },
           {
            headers: {
                
                'Content-Type': 'application/json',
            }
        },
          
          ).then(function(response) { 
    
      const result = response.data

      console.log(result)
      if(result && result.Message)  {

        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(result))
      }
      
  }).catch((e)=> {
  
            console.log(e)  
    res.send(false)
         
  })
} catch (error) {
     
  console.log(error)
  res.send(false)
}
 });

这就是我在我的 React 应用程序中发出请求的方式

export  async function sendContact(request){

    try {
        

        if(!request.Phone)
            request.Phone = false

        if(request.textMe){
            request.type = "BOTH"
        }
        else{
            request.type = "EMAIL"
        }    
            let result ;
           await fetch('/contact', {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ 
                    Email : request.Email,
                    type : request.type,
                    Message : request.Message,
                    Phone : request.Phone
                 }) 
                }
                
                ).then(async response => 
                    await response.json()
                ).then(data => 
                         result = data 
                ).catch((e)=> { 
                    notifyError(e.response.data.Message) 
                    return false           
                })
        console.log(result)
    return result

} catch (error) {
        
    console.log(error)
}
              
}

最后,这是我的应用程序的 Amplify 构建脚本

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm i
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/* 

PS:我也有"proxy": "http://localhost:5000"添加到我的 Package.json

EDIT :

我尝试使用后台任务管理器,例如PM2 https://www.npmjs.com/package/pm2在构建脚本中运行构建后,但这仍然不起作用(尽管它在本地运行)


我最终在客户端和服务器之间建立了一个代理 lambda 作为我的 API 网关(中间人)。我还有代理拒绝任何不是来自我的网站的请求。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 AWS Amplify 上运行 React/Redux 应用程序的代理 的相关文章

随机推荐