Search code examples
javascriptajaxfetchpreflight

Preflight Request failing with the window.fetch api


Let me preface this by saying it's working in POSTMAN, Chrome's add-on API client. But it's not working in my actual application, and I'm wondering if there's something I've forgotten to include in the fetch request.

I have the following request.

(id, vzId)=>{
            var json = {id: id, vzId: vzId, };
            var request = {
                method: 'POST', 
                body: json,
                headers: new Headers({
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                })
            }
            fetch('http://localhost:8080/notification/markRead',request).then(function(response){
                return response.json();
            }).then(function(json){
                console.log(json);
            })
        }

When the request is triggered, it returns me this error.

OPTIONS http://localhost:8080/notification/markRead 
Fetch API cannot load http://localhost:8080/notification/markRead.   
Response for preflight has invalid HTTP status code 403

I used the exact same url and data in my chrome rest client (POSTMAN) and it's working, but for some reason it isn't working when I use the FETCH api. Any help would be much appreciated.


Solution

  • In case anyone stumbles on this and it can help people in the future, we found the answer. There's nothing wrong with the code I posted. The reason it was working on Postman and not the client is because Postman doesn't do a preflight request. The client (as pretty much all websites will do), sent a preflight request, in the form of an OPTIONS method. The backend Spring server wasn't allowing the options method. The backend developer had to allow the OPTIONS method to the specific route in the server, not just the POST.

    So in the case you're testing on Postman but can't duplicate the behavior, remember that Postman doesn't send a preflight request.