【问题标题】:How to use a proxy for a link with reactjs如何使用代理与 reactjs 建立链接
【发布时间】:2019-06-09 09:50:15
【问题描述】:

我正在开发一个网站,前端使用 Reactjs 和 Typescript,后端使用 Java。在开发过程中,我将端口 3000 用于前端,将 8080 用于后端。我已经在 package.json

上设置了代理属性
"proxy": "http://localhost:8080"

所以我在向后端发出请求时没有任何问题,因为代理运行良好。

现在我需要创建一些链接来下载报告,所以我动态生成链接,我需要它们指向端口 8080 而不是端口 3000强>

我正在传递这样的网址:

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

this.state.url 看起来像 /reports/download/users 并且它指向 http://3000/reports/download/ 是有意义的用户

知道如何在 dev 中创建指向 8080 端口的链接。

更新

代理正在处理类似以下代码的请求:

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

但是当我生成一个 url 链接时它不起作用:

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

【问题讨论】:

  • 代理不就是这样做的吗?您请求http://localhost:3000/reports/download/users,而代理将其指向:8080。使用代理的好处是,即使前端和后端在 dev 中的不同端口上运行,您也可以对所有内容使用 相对 路由。
  • 是的,但它在链接上不起作用,就在我通过 fetch 请求某些东西但当我使用 url 链接时总是指向端口 3000(我的意思是前端)@​​jonrsharpe跨度>
  • 当您点击代理时,代理是否工作?
  • 没有。代理仅在 ajax 请求时工作,但在链接始终指向前端端口的情况下。我不知道如何解决这个问题。

标签: reactjs typescript react-router


【解决方案1】:

我使用了一个我认为不是很好的解决方案,但它对我有用。

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

你可以有一些指向你的开发服务器的全局变量,你可以使用它来代替http://localhost:8000

【讨论】:

    【解决方案2】:

    您不应使用proxy 属性来设置后端基本网址。 As per the doc:

    请记住,proxy 仅在开发中有效(使用 npm start),您可以确保像 /api/todos 这样的 URL 指向生产中的正确内容。

    当您构建应用时,它不会工作。

    您应该为您的后端基本 URL add an environment variable 并在您进行后端调用时添加它。

    类似

       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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      相关资源
      最近更新 更多