简体   繁体   中英

Error sending AJAX POST request from local .html file to localhost:8080. CORS: "It does not have HTTP ok status."

I am getting an error when attempting to send a POST via AJAX from my own .html and .js files to localhost:8080. Upon submitting the request, the full error reads: "Access to XMLHttpRequest at ' http://localhost:8080/contact/new-message ' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

CORS is already enabled on my browser, so access is automatically "Access-Control-Allow-Origin : *", so this is a different from that error.

Is there a way to include an "ok" status in the header? Or is the problem arising from elsewhere? Any help is greatly appreciated. Here are some code snippets:

My JavaScript, which runs as part of a form-submission:

function submitMessageAJAXCall(inputName, inputEmail, inputMessage, inputRegion) {
    $.ajax({
        type: 'POST',
        url: 'http://localhost:8080/contact/new-message',
        data: JSON.stringify({
            rbName: inputName,
            rbEmail: inputEmail,
            rbMessageText: inputMessage,
            rbRegionId: inputRegion
        }),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        success: function() {

            alert('Success!');
            displayThankYouMessage();

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('Unfortunately that message did not go through.');
        }
    }); 
}

The Java code which recieves it:

@PostMapping("/new-message")
    private ResponseEntity<HttpStatus> addNewMessage(@RequestBody RBNewMessage rbNewMessage) {
        //validate message in service layer
        boolean isRequestValid = contactService.validateNewMessageRB(rbNewMessage);

        //is message is good, save it; else, return an error
        if (isRequestValid == true) {
            //create a new message
            ContactMessage message = new ContactMessage();

            //set message fields
            message.setMyName(rbNewMessage.getRbName());

            message.setMyEmail(rbNewMessage.getRbEmail());

            message.setMessageText(rbNewMessage.getRbMessageText());

            LocalDateTime timeOfMessage = LocalDateTime.now();
            LocalDateTime timeWithoutNano = timeOfMessage.withNano(0);
            message.setTimeStamp(timeWithoutNano);

            int regionId = rbNewMessage.getRbRegionId();
            Region region = regionService.getRegionById(regionId);
            message.setRegion(region);

            ContactStatus cs = contactStatService.getStatusById(1);     
            message.setContactStatus(cs);

            //save message
            contactService.save(message);

            //return success
            return new ResponseEntity<>(HttpStatus.OK);

        } else {
            //return error
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

And this is an example of a Postman request that is successful:

{
    "rbName": "John Johnson",
    "rbEmail" : "JohnJohnson@Email.com",
    "rbMessageText" : "Hello there, this is my message.",
    "rbRegionId" : 5
}

将@CrossOrigin 注释(导入 org.springframework.web.bind.annotation.CrossOrigin)添加到处理请求的控制器类的顶部。

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