'ReactJS/Springboot- Blocked by CORS policy: No 'Access-Control-Allow-Origin'

I am working on a project with Springboot ReactJS and MongoDB. I have implemented the whole code but it doesn't import data from the database. It shows the below error.

Access to XMLHttpRequest at 'http://localhost:8080/api/auth/file' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I go through the solutions I found through StackOverflow and tried the below ways to solve this,

  1. Adding @crossorigin
  2. Adding the chrome extension
  3. npm install cors

But it still doesn't work.

I would be glad if anyone could help me to solve this issue.

Controller

    package com.spring.mongodb.controllers;

import com.spring.mongodb.models.LogFile;
import com.spring.mongodb.models.LogRecord;
import com.spring.mongodb.models.LogRecordCollection;
import com.spring.mongodb.payload.request.BackupRequest;
import com.spring.mongodb.payload.request.DeleteFileRequest;
import com.spring.mongodb.repository.LogFileRepository;
import com.spring.mongodb.repository.LogRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@RestController
@CrossOrigin(origins = "http://localhost:8081")
@RequestMapping("/api/auth/file")
public class LogFileController {

    @Autowired
    LogFileRepository logFileRepository;
    @Autowired    private LogRecordRepository logRecordRepository;

    @GetMapping("")
    public ResponseEntity<?> getAllLogFiles() {
        try{
            List<LogFile> logFiles = logFileRepository.findAll();
            return ResponseEntity.ok().body(logFiles);
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(e.getMessage());
        }
    }
    @DeleteMapping
    public void deleteFiles(@Valid @RequestBody DeleteFileRequest request) {
        List<String> recordIds = request.getRecordIds();
        for (String recordId : recordIds) {

            logFileRepository.deleteById(recordId);
            LogRecordCollection collection = new LogRecordCollection();
            collection.setCollectionName(recordId);
            logRecordRepository.deleteAll();
        }
    }
}

Request sending from frontend

await axios
        .get("http://localhost:8080/api/auth/file")
        .then((res) => {
          console.log(res);
          this.setState({
            folders: res.data,
          });
        })
        .catch(function (error) {
          console.log(error);
        });
    this.setState({
      loading: true
    })


Solution 1:[1]

You can try by adding the http component dependency and then give the cross origin value in controller class, You have to mentioned a link in cross origin from where your RESTfull api will get called

Dependency

  <dependency>   
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <scope>test</scope>
  </dependency>`

Like below you can add the cross origin value in controller

 @CrossOrigin(origins = "http://localhost:8081")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nutan