简体   繁体   中英

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. 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. 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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