每当我在反应JS的搜索表单上提交关键字时,我都会尝试访问我的twitter api。通过API获取推文的春季启动代码正在运行,我可以在网址http://localhost:8081/trend/twitter?keyword=selena上访问它。现在我正在尝试在我的反应JS表单上连接此API,所以当我搜索关键字时,我会通过反馈来访问Twitter此API调用并显示结果。我从早上开始浏览在线代码,我一直在尝试所有的建议,但到目前为止还没有任何工作。
我在控制台上收到此错误消息
无法加载资源:服务器响应状态为403()twitter:1来自原始'http://localhost:8081/trend/twitter?keyword=douglas'的'http://localhost:3000'获取访问权限已被CORS策略阻止:没有'Access-Control-Allow-Origin'标头存在在请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。
Spring Boot Code
@RestController
@RequestMapping("/trend")
public class TwitterController {
private TwitterService twitterService = new TwitterService();
// Get all tweets by keyword
@GetMapping("/twitter")
@CrossOrigin(origins = "http://localhost:3000/")
public List<Tweet> getTweets(@RequestParam("keyword") String keyword) {
return twitterService.getTweets(keyword);
}
ReactJS代码
class App extends Component {
getTrend = async (e) => {
e.preventDefault();
const keyword = e.target.elements.keyword.value;
const api_call = await fetch(`http://localhost:8081/trend/twitter?keyword=${keyword}`); //make API call
// axios.get('http://localhost:8081/trend/twitter?keyword=${keyword}')
//.then((res) => {
console.log(api_call);
// });
}
render() {
return (
<div>
<div class="col-sm-9">
<SearchEngine getTrend={this.getTrend} />
</div>
</div>
);
}
}
export default App;
您尝试在http://localhost:3000/
上启用CORS,但需要http://localhost:8081