简体   繁体   English

如何在React JS上访问Spring Boot API

[英]How to access Spring Boot API on React JS

I am trying to access my twitter api whenever I submit a keyword on the search form on react JS. 每当我在react JS的搜索表单上提交关键字时,我都试图访问我的twitter api。 The spring boot code fetching Tweets via the API is working and I can access it on the url http://localhost:8081/trend/twitter?keyword=selena and Now I am trying to connect this API on my react JS form so when ever I search for a keyword on react it will access to twitter via this API call and display the results. 通过API获取Tweets的spring boot代码正在运行,我可以在url http:// localhost:8081 / trend / twitter?keyword = selena上访问它,现在我尝试在我的React JS表单上连接此API,因此当每当我在react上搜索关键字时,它将通过此​​API调用访问twitter并显示结果。 I have been browsing through online codes since morning and I have been trying all the suggestions but nothing is working till now. 自早上以来,我一直在浏览在线代码,并且一直在尝试所有建议,但到目前为止没有任何工作。

I get this error message on my console 我在控制台上收到此错误消息

Failed to load resource: the server responded with a status of 403 () twitter:1 Access to fetch at ' http://localhost:8081/trend/twitter?keyword=douglas ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载资源:服务器的响应状态为403()twitter:1访问从源地址' http:// localhost:3000 '获取的' http:// localhost:8081 / trend / twitter?keyword = douglas '已被CORS策略阻止:所请求的资源上没有“ Access-Control-Allow-Origin”标头。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 如果不透明的响应满足您的需求,请将请求的模式设置为“ 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 Code 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM