【问题标题】:React JS: no answer from Sinatra server with fetch callReact JS:没有来自 Sinatra 服务器的 fetch 调用应答
【发布时间】:2017-06-29 07:45:55
【问题描述】:

我对 Sinatra 和 React JS 很陌生,因此我只想在 Sinatra 服务器上从我的 React 网站进行 GET 调用以显示纯文本。

Sinatra 服务器:

require 'sinatra'

set :root, 'lib/app'

before do
  response.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080'
  response.headers['Accept'] = 'gridoperator'
  response.headers['Content-Type'] = 'gridoperator'
end

get '/gridoperator' do
  'Hello root gridoperator'
end

反应 JS:

var Gridoperator_div = React.createClass({

  getInitialState: function(){
    return({
      call_name: 'initial'
    });
  },

  componentDidMount: function(){

    fetch('http://localhost:4567/gridoperator', {
      method: 'get'
    }).then(response => response.text())
    .then(
        function(text){
          this.setState({
            call_name: text
          })
    });

  },

  componentWillUnmount: function(){
  },

  render: function() {
    return(
        <h1>Hello {this.state.call_name}!</h1>
    )
  }

});

ReactDOM.render(<Gridoperator_div/>, document.getElementById('gridoperator'));

Sinatra 服务器已经过 REST 测试,应该可以工作。

不幸的是,如果我想连接我的 React 网站,我只能阅读以下内容:

enter image description here

在日志中识别出我的 React 网站的连接:

::1 - - [10/Feb/2017:21:28:00 +0100] "GET /gridoperator HTTP/1.1" 200 23 0.0000
::1 - - [10/Feb/2017:21:28:00 Mitteleuropõische Zeit] "GET /gridoperator HTTP/1.1" 200 23
http://localhost:8080/ -> /gridoperator

我真的希望有人可以帮助我,因此提前致谢!

编辑

我忘记了一些事情,如果我启动我的网站,它会编译并带有警告:

WARNING in ./~/encoding/lib/iconv-loader.js
Critical dependencies:
9:12-34 the request of a dependency is an expression
 @ ./~/encoding/lib/iconv-loader.js 9:12-34
webpack: Compiled with warnings.

【问题讨论】:

  • 您是否在浏览器 javascript 控制台中查看过错误?

标签: javascript ruby reactjs sinatra fetch-api


【解决方案1】:

如果没有看到更多,很难说出确切的问题是什么,但如果我不得不猜测,我会说这可能与 CORS 预检有关,因为你得到的回报太少了。这也解释了为什么可以加载静态内容。

看起来您正在使用response.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080' 手动滚动您自己的逻辑。您没有设置所有 CORS 标头,这可能是请求未通过的原因。请参阅Mozilla documentation 了解更多信息。

手动滚动这种逻辑几乎总是一个坏主意。查看https://github.com/cyu/rack-corshttps://github.com/britg/sinatra-cross_origin。我推荐前者。它易于配置,一旦设置好,您就可以或多或少忘记它。

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多