【问题标题】:Unable to fetch the data from spring boot app in React app [duplicate]无法从 React 应用程序中的 Spring Boot 应用程序获取数据 [重复]
【发布时间】:2019-03-16 06:38:10
【问题描述】:

我正在将 Spring Boot 应用程序和 React 应用程序链接起来,但不幸的是,在从引导应用程序获取数据时,我遇到了如下所述的错误。

AppCrypto.js:22 选项http://localhost:8080/secretdata/allcurrency/403

crypto:1 访问从源“http://localhost:3000”获取“http://localhost:8080/secretdata/allcurrency/”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

下面是代码sn-ps。

import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import {Jumbotron,Button,Table} from 'react-bootstrap';

class AppCrypto extends Component{

  constructor(props) {
  super(props);
  this.state = {currencies: null};
}



componentDidMount() {
  const requestOptions = {
      method: 'GET',
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*' }
  };
   fetch('http://localhost:8080/secretdata/allcurrency/',requestOptions)
        .then(results => {
          return results.json();
        })
        .then(data => {
          let currencies =data.results.map((curr) =>{
            return(
              <Table>
                 <thead>
                  <tr>
                    <th>ID</th>
                    <th>CURRENCY_NAME</th>
                    <th>CURRENCY_TICKER</th>
                  </tr>
                 </thead>
                 <tbody>
                    <tr>
                       <td>{curr.id}</td>
                       <td>{curr.currencyname}</td>
                       <td>{curr.currencyticker}</td>
                    </tr>
                 </tbody>
              </Table>
            )
          })
          this.setState({currencies:currencies});
          console.log("state",this.state.currencies);
})

}

  render(){
    return(
      <div className="container2">
        <div className="container1">
         {this.state.currencies}
        </div>
        </div>

    );
  }
}



export default AppCrypto;
package de.ohmstr.secretdata;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(path="/secretdata/")
public class SecretDataController {

    @Autowired
    private SecretDataRepository sdr;

    @PostMapping (path="/currency/")
    public @ResponseBody String retrievCurrency(@RequestParam String currencyname, @RequestParam String currencyticker){

        SecretData sd=new SecretData();
        sd.setCurrencyname(currencyname);
        sd.setCurrencyticker(currencyticker);
        sdr.save(sd);
        return "saved";
    }

    @GetMapping (path="/allcurrency/")
    public @ResponseBody Iterable<SecretData> getAllCurrencies(){
        return sdr.findAll();
    }

    @GetMapping (path="/getmessage/")
    public @ResponseBody String getMessage(){
        return "Welcome to my Secret World";
    }



}

【问题讨论】:

  • 由于您的后端位于不同的端口上,因此基本上将其视为不同的域。您可以设置代理以使用后端将请求转发到正确的端口。如果您使用的是create-react-app,请参阅docs about proxies here
  • 感谢代理提示。我在 package.json 中添加了代理,但出现以下错误。未处理的拒绝(TypeError):无法读取未定义(匿名函数)的属性“映射”F:/secret/secretapp/src/components/AppCrypto.js:20 17 |返回结果.json(); 18 | }) 19 | .then(data => { > 20 | 让货币 =data.results.map((curr) =>{ | ^ 21 | return( 22 | 23 |

标签: javascript spring reactjs spring-boot


【解决方案1】:

您可能会获得未定义的货币,我希望您已确保获得数据,但由于控制台抛出错误,在某些时候您可能会获得未定义的数据。 我只是将条件添加到您的 .then 处理程序中,

let currencies =(data.results || []).map((curr)
=>{ return( <Table> <thead> <tr> <th>ID</th>
<th>CURRENCY_NAME</th>
<th>CURRENCY_TICKER</th> </tr> </thead> 
<tbody>
 <tr> <td>{curr.id}</td> <td>{curr.currencyname}
</td>
 <td>{curr.currencyticker}</td> </tr> </tbody>
 </Table> ) }) 
this.setState({currencies:currencies}, ()=>{ 
 console.log(this.state));

【讨论】:

  • 我已经修改了下面提到的代码。但是我得到的错误是错误:------- 43 | CURRENCY_TICKER 44 | 45 | > 46 | | ^ 47 | {this.state.currencies.map(function(item, key){ 48 | return( 49 | 更新代码:---- {this.state.currencies.map(function(item, key){ return( item.id item.currencyname item.currencyticker ) }) }
猜你喜欢
  • 2021-08-17
  • 2021-02-20
  • 1970-01-01
  • 2016-11-30
  • 2020-08-02
  • 2022-01-20
  • 2021-06-14
  • 2017-07-03
  • 2017-06-25
相关资源
最近更新 更多