Suppose I have two servers A and B:
A -> React App server
B -> API Server (in my case Node with Express)
Both of which I have control.
I have CORS enabled on server B, and on development am using proxy in my client app's package.json to query the API server.
Now the problem is when I send a GET request from server A to the API server and ask it to do a redirect to another external URL I get a CORS error in my React App.
But, when I make a GET request to the API server via Postman I am redirected. I understand that it happens because the react app server is not registered with CORS while the API server is.
And this issue can be mitigated if both the applications are on the same server. Correct me if I am wrong?
Am currently doing a workaround by making a GET request to the API server, getting the redirect URL as a response and doing a redirect on the client side.
Now my question is, whether there is any other possible way in which I don't have to get the redirect url as a response/ put both applications on same server and instead do a redirect straightaway?
I want the request flow to be:
React App [app.com] ----GET----> Api server[api.app.com]) ----REDIRECT----> External URL
My current implementation:
API Snippet
try {
let url = await Urls.findOne({ shortCode: shortCode });
if(!url) {
// Send 404
return res.status(404).send({ status: "NOT_FOUND" });
}
// Redirect to original URL
//res.redirect(url.longUrl);
return res.status(200).send({ status: "FOUND", url: url.longUrl });
}
catch(error) {
console.log(error);
return res.status(500).send({ status: "FAILED" });
}
Client Side
componentDidMount() {
let id = this.props.match.params.id;
axios.get(`/api/${id}`)
.then(response => {
window.location.replace(response.data.url);
})
.catch(error => {
this.setState({ displayError: true, errorType: error.response.data.status })
});
}