2014-10-20 51 views
2

3000网址交叉张贴到https://github.com/andreypopp/react-async/issues/34摆脱本地主机:用于ReactAsync

当使用react-async是经常会有的代码看起来像:

var UserPage = React.createClass({ 
    mixins: [ReactAsync.Mixin], 

    statics: { 
    getUserInfo: function(username, cb) { 
     superagent.get(
     'localhost:3000/api/users/' + username, 
     function(err, res) { 
      cb(err, res ? res.body : null); 
     }); 
    } 
    }, 

    getInitialStateAsync: function(cb) { 
    this.type.getUserInfo(this.props.username, cb); 
    }, 

    ... 

这里的问题是,它在服务器上运行的浏览器中正确运行。

使用相对使URL的显而易见的解决方案(如'/api/users/' + username有一个微妙的问题。

看来工作,当移动页面之间,但在重新加载页面或初始负载不工作。(其实你不在ReactJS应用程序页面之间移动,它只是改变了URL)。

这个问题的原因是服务器需要调用AJAX API,服务器端渲染过程中,但服务器不知道浏览器所见的页面源(http://www.example.com:3000)。

有没有办法告诉服务器端的渲染器?

(我已经想到了一个肮脏的工作,各地,在您使用完整的URL为客户端和服务器,但必须明确为运行代码的每一开发,测试和生产服务器进行配置。)

+1

我在想出一个解决的办法(仅使用AngularJS)的过程,所以我很感兴趣看看这是怎么回事。 – 2014-10-20 12:23:02

+0

@IBrindley AngularJS能渲染服务器端吗? – fadedbee 2014-10-20 12:31:59

+1

纯粹是实验性的。我从来没有深入研究React,所以我只是将耳朵放在地上。 – 2014-10-20 12:43:27

回答

3

要开始,请使用superagent的简单插件函数。这会重写绝对网址 - 但只能在服务器上。这意味着浏览器会向'/ api'发送请求,服务器会将其设置为'localhost:port/api'。

function fixUrlPlugin(port){ 
    return function fixUrl(req){ 
    if (process.browser) return req; 
    if (req.url[0] === '/') { 
     req.url = 'localhost:' + port + req.url 
    } 
    return req; 
    }; 
} 

现在在你的代码中的某个地方,你会运行它并将输出保存在一个模块中。

app.listen(8080); 
module.exports = fixUrlPlugin(8080); 

然后你的代码可以进来:

var urlPlugin = require('./path/to/that/module.js'); 

// ... 

    statics: { 
    getUserInfo: function(username, cb) { 
     superagent.get('/api/users/' + username) 
     .use(urlPlugin) 
     .end(function(err, res) { 
      cb(err, res ? res.body : null); 
     }); 
    } 
    }, 
+0

谢谢,这看起来像一个不错的解决方案。我会试一试。 – fadedbee 2014-10-21 11:45:59