【发布时间】: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