I have recently Implemented Proxy (in Express.js) for my React App to hide API URL's when making a request. 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. Do I need to use an EC2 instance instead or can I achieve this using Amplify?
Any Help would be greatly appreciated!
This is what my Project Directory Looks like :
This is what my Server.js looks like :
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
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
version: 1
frontend:
phases:
preBuild:
commands:
- npm i
build:
commands:
- npm run build
artifacts:
baseDirectory: build
files:
- '**/*'
cache:
paths:
- node_modules/**/*
P.S : I do also have "proxy": "http://localhost:5000" added to my 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)
from How to run proxy for react/redux application on AWS Amplify

No comments:
Post a Comment