【问题标题】:Is there a way to call api with only different sub domains in React?有没有办法在 React 中只使用不同的子域调用 api?
【发布时间】:2020-12-01 14:49:09
【问题描述】:

我第一次做React项目的时候,只有一个宿主域api,所以我通过修改包文件的代理值来使用它。 (我更喜欢使用代理,因为我遇到了 cors 问题。)

最近使用http-proxy-middleware 使用了两个以上的主机域api,使用如下。

module.exports = function(app){
    app.use(createProxyMiddleware('/call1', { target : 'http://sub.host1.com' }));
    app.use(createProxyMiddleware('/call2', { target : 'http://sub.host2.com' }));
    app.use(createProxyMiddleware('/call3', { target : 'http://sub.host3.com' }));
}  

问题是我想调用相同的 API,但只有子域不同,但我不知道如何。

前)

sub1.host1.com/call1

sub2.host1.com/call1

sub3.host1.com/call1

如果您有任何想法,请告诉我。 谢谢。

【问题讨论】:

    标签: reactjs proxy cross-domain http-proxy-middleware


    【解决方案1】:

    我解决了 pathRewrite 的问题。

    【讨论】:

    • 怎么样?你能分享一下你的解决方案吗?
    • @NiuhuruLang app.use(createProxyMiddleware('/a',{ target:'aaa.com:9002', secure:false, pathRewrite:{ '^/a/' : '/' } } ) ) app.use(createProxyMiddleware('/b',{ target:'bbb', secure:false, pathRewrite:{ '^/b/' : '/' } } ))
    【解决方案2】:

    希望对你有所帮助。

    server.use(
      '/api',
      createProxyMiddleware({
        target: 'https://sub.domain.com/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      })
    );
    

    【讨论】:

    • 社区鼓励在代码中添加解释,而不是纯粹基于代码的答案(参见here)。
    猜你喜欢
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2021-02-19
    • 2019-01-29
    相关资源
    最近更新 更多