使用React与Nashorn抛出" ReferenceError:" console"没有定义"

时间:2014-12-24 12:14:40

标签: java javascript reactjs nashorn

我正在使用"react": "~0.12.2"

以下代码:

@RequestMapping("/")
@ResponseBody
private String home() throws ScriptException, IOException {
    loadReact();
    InputStream jsStream = resourceLoader.getResource("classpath:public/js/server.js").getInputStream();
    engine.eval(new InputStreamReader(jsStream));
    return engine.eval("renderServerside()").toString();
}

private void loadReact() throws ScriptException, IOException {
    InputStream jsStream = resourceLoader.getResource("classpath:public/lib/react/react.js").getInputStream();

    // React expects 'window' or 'global' to be set
    engine.eval("var global = this");
    engine.eval(new InputStreamReader(jsStream));
}

我的server.js看起来像这样:

function renderServerside() {
    var MyComponent = React.createClass({
        render: function () {
            return React.DOM.h1(null, 'Hi, ' + this.props.msg)
        }
    });

    return React.renderComponentToString(MyComponent({msg: 'World!'}));
}

得到这个例外:

javax.script.ScriptException: ReferenceError: "console" is not defined in <eval> at line number 18108] with root cause

jdk.nashorn.internal.runtime.ECMAException: ReferenceError: "console" is not defined

那么nashorn怎么能不提供控制台?

我厌倦了从这个页面实现基本示例:React with Nashorn

1 个答案:

答案 0 :(得分:6)

Rhino之前它也没有提供。您可以使用类似

的方式实现自己的控制台
console = { 
    log: print,
    warn: print,
    error: print
};

对于完整的控制台支持,您可能需要添加更多功能。请参阅:Console