我正在链接Spring Boot应用程序和React应用程序,但是不幸的是,当从Boot App中获取数据时,我遇到了如下所述的错误。
AppCrypto.js:22个选项http://localhost:8080/secretdata/allcurrency/ 403
crypto:1已被CORS策略阻止从源“ http://localhost:8080/secretdata/allcurrency/”到“ http://localhost:3000”的访存: 对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。
下面是代码段。
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";
}
}
答案 0 :(得分:0)
您可能会获得未定义的货币,我希望您已确定已获取数据,但由于控制台抛出错误,有时您可能会获得未定义的货币。 我只是向您的.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));