如何在基于ReactJS的节点应用程序中从外部API获取服务器端的数据?

问题描述 投票:2回答:2

我努力在React-App中从外部API获取数据。但它总是给我以下错误:

请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,'http://api.example.com'原产地不允许进入。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。

这是我的代码:

// @flow

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

const URL = 'http://api.example.com/my/api/request' // obfuscated

class App extends Component {

  componentDidMount() {
    fetch(URL).then( response => {
      console.log(response);
    })  
    .catch(err => {
      console.log(err);
    })
  }

  render() {
    return (
      <div className="App">
      <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small>
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React!</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

据我所知,只有客户端请求才需要CORS-thing,而不是服务器端请求。

谁能帮我?

javascript node.js reactjs
2个回答
1
投票

服务器端永远不会调用componentDidMount钩子。因此,只有在将应用程序装入DOM后,您的提取代码才会在浏览器中运行。要从服务器获取数据,您可以在componentWillMount钩子中使用fetch,它将在服务器上调用,但也在客户端上调用。


0
投票

您必须在服务器上调用api请求,等待响应并返回呈现的html页面。

我已经为服务器端渲染https://github.com/gzoreslav/react-redux-saga-universal-application创建了一个启动器

它使用redux和redux-saga

© www.soinside.com 2019 - 2024. All rights reserved.