简体   繁体   English

如何在 AWS Amplify 上为 react/redux 应用程序运行代理

[英]How to run proxy for react/redux application on AWS Amplify

I have recently Implemented Proxy (in Express.js) for my React App to hide API URL's when making a request.我最近为我的React 应用程序实现了代理(在 Express.js 中)以在发出请求时隐藏 API URL。 It has been working perfectly fine when I run it the proxy and app on localhost.当我在本地主机上运行代理和应用程序时,它一直工作得很好。 Now that I'm ready to deploy My application to AWS Amplify , I am a little confused as to how I get my proxy to run there since I'm not manually starting the app and proxy from the CLI.现在我已经准备好将我的应用程序部署到AWS Amplify ,我对如何让我的代理在那里运行感到有些困惑,因为我没有从 CLI 手动启动应用程序和代理。 Do I need to use an EC2 instance instead or can I achieve this using Amplify ?我是否需要使用EC2 实例,或者我可以使用Amplify实现这一点吗?

Any Help would be greatly appreciated!任何帮助将不胜感激!

This is what my Project Directory Looks like :这是我的项目目录的样子:

项目目录

This is what my Server.js looks like :这是我的 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)
}
 });

And this is how I make the request from In my React App这就是我在我的 React App 中发出请求的方式

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)
}
              
}

And Finally, Here's My Build Script from Amplify for my application最后,这是我的应用程序的 Amplify 构建脚本

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

PS : I do also have "proxy": "http://localhost:5000" added to my Package.json PS:我也有"proxy": "http://localhost:5000"添加到我的Package.json

EDIT :编辑 :

I tried Using a Background task manager like PM2 to run post build in the build script but that still did not work (although it did locally)我尝试使用像PM2这样的后台任务管理器在构建脚本中运行后期构建,但这仍然不起作用(尽管它在本地完成)

The proxy field in package.json is a feature from Create React App to ease local development to avoid common CORS issues. package.json 中的 proxy 字段是 Create React App 的一项功能,用于简化本地开发以避免常见的 CORS 问题。

It cannot be used in a production environment.不能在生产环境中使用。 ( Source ) 来源

I ended up spinning up a proxy lambda as my API gateway (middle man) between my client and server.我最终在我的客户端和服务器之间启动了一个代理 lambda 作为我的 API 网关(中间人)。 I also have the proxy denying any requests not coming from my website.我还让代理拒绝任何不是来自我网站的请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM