How to use a proxy for a link with reactjs

Viewed 2643

I'm working on a website using Reactjs and Typescript for the front-end and the backend is in Java. While I'm developing I use port 3000 for the frontend and the 8080 for the backend. I have setup the proxy property on the package.json

"proxy": "http://localhost:8080"

so I don't have any problem while I'm doing requests to the backend because the proxy works perfectly.

Now I need to create some links to download reports, so I'm generating dynamically the links and I need them to point to the port 8080 and not to the port 3000

I'm passing the url like:

<a href={this.state.url}>Download Report</a>

where this.state.url looks like /reports/download/users and make sense its pointing to http://3000/reports/download/users

Any idea how to create the links in dev to point to the port 8080.

Updated

The proxy is working with a request like the below code:

   fetch('./app/admin/reports/availableReports')
    .then(res => res.json())
    .then(json => json.reportTypes)
    .catch(ex => {
        console.log('Alert!!', ex)
        return []
    })

But its not working when I generate a url link:

<a href={'app' + this.state.currentDownloadUrl}>Download Report</a>
2 Answers

I used one not a very good solution I think, but it works for me.

<a href={`http://localhost:8000${record_detail_item.file}`} download>Download File</a>

You can have some global variable which points to your dev server and you can use it instead of http://localhost:8000

You shouldn't use the proxy property to set the backend base url. As per the doc:

Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production.

When you build your app, it won't work.

You should add an environment variable for your backend base URL and prepend it when you make backend calls.

Something like

   fetch(`${process.env.REACT_APP_API_ENDPOINT}/app/admin/reports/availableReports`)
    .then(res => res.json())
    .then(json => json.reportTypes)
    .catch(ex => {
        console.log('Alert!!', ex)
        return []
    })
<a href={`${process.env.REACT_APP_API_ENDPOINT}${this.state.currentDownloadUrl}`}>Download Report</a>
Related