Labelle Doriane
Labelle Doriane

Reputation: 115

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;

Upvotes: 0

Views: 638

Answers (1)

Alexey Semenyuk
Alexey Semenyuk

Reputation: 3303

You try to enable CORS on http://localhost:3000/, but need http://localhost:8081

Upvotes: 1

Related Questions