skip to Main Content

I have such function to retrieve data from my form and send them to Spring Boot server

function saveDataToStorage(event){
            event.preventDefault();
            let name = document.getElementById('imie').value;
            let email = document.getElementById('email').value;
            let phone = document.getElementById('telefon').value;
            let topic = document.getElementById('temat').value;
            let message = document.getElementById('wiadomosc').value;
            let data = {
                name: name,
                email: email,
                phoneNumber: phone,
                topic: topic,
                text: message
            }

            fetch('http://localhost:8080/api/endpoint',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
                .then(response => response.json())
                .then(data => {console.log('Success:',data);})
                .then(error => {console.log('Error:',error);});

            document.getElementById('imie').value = '';
            document.getElementById('email').value = '';
            document.getElementById('telefon').value = '';
            document.getElementById('temat').value = '';
            document.getElementById('wiadomosc').value = '';
        }

also have class FormData

@Data
@AllArgsConstructor
public class FormData {
    String name;
    String email;
    String phoneNumber;
    String topic;
    String message;
}

POST endpoint

@PostMapping("/api/endpoint")
    public ResponseEntity<String> receiveData(@RequestBody FormData data){
        log.info(data.getName()+" "+data.getEmail()+" "+data.getPhoneNumber()+" "+data.getTopic()+" "+data.getMessage());
        return ResponseEntity.ok("data recieved");
    }

When i submit form data in website i recieve such error

Failed to load resource: the server responded with a status of 403 ()

In the spring app console i dont have any errors

I have tried to add to my security config authorization to this endpoint

http.authorizeHttpRequests(authz->authz
.requestMatchers("/api/endpoint").permitAll()

but it did not change anything

2

Answers


  1. Chosen as BEST ANSWER

    Problem was solved by adding those tags to the head

    meta name="_csrf" th:content="${_csrf.token}" meta name="_csrf_header" th:content="${_csrf.headerName}"

    and this code to the script

     let csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
                    let csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
                    fetch('http://localhost:8080/api/endpoint',{
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            [csrfHeader]: csrfToken
                        },
                        body: JSON.stringify(data),
                    })
    

  2. Maybe cross-origin request (CORS) configuration is missing? It’s difficult to tell without seeing the class-level annotations for the controller.

    If it is, try adding @CrossOrigin("*") or @CrossOrigin(origins = "[origin address]") annotation above the class declaration in the controller. Note: wildcard cross origin must not be used in production.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search