Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a proxy for a link with reactjs

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>
like image 733
gon250 Avatar asked Jan 15 '19 11:01

gon250


People also ask

How do I use a proxy server in React?

Proxy Setup with Create-React-App All you have to do is add a proxy field to your package. json file, like shown below. "proxy": "http://localhost:3000", This line instructs the development server to proxy any unknown requests to your API server in development mode.

Where do I put proxy in package json in React?

To configure the proxy, you'll need to add the following line to your package. json . Then, in your React app, you can make API requests by using relative paths. For example, http://localhost:8000/api/todos becomes /api/todos .


1 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

  • Update: Instead of hardcoding URL, you can set up environment variables Create-react-app environment variables
like image 65
Jasurbek Nabijonov Avatar answered Oct 22 '22 00:10

Jasurbek Nabijonov