Response from pre-flight failing with Status 405

2019-08-19 00:16发布

问题:

I'll start by saying I'm a bit of a newb when it comes to Javascript/React. I am attempting to communicate with my WCF endpoint server but I can’t seem to send any POST messages without getting a response:

OPTIONS http://###/testbuyTicket 405 (Method Not Allowed)

It seems that because I am sending it with content-type JSON it requires a ‘pre-flight’ and this is where it is failing.

This is my client code:

    var headers = {
        'headers': {
            'Content-Type': 'application/json',
        }
    }

    axios.post(call, data, headers).then(res => {
        try {
            if (res) {}
            else {
                console.log(res);
            }
        }
        catch (err) {
            console.log(err);
        }
    }).catch(function (error) {
        console.log(error);
      });

Here is the error details:

I don’t see why this pre-flight is failing. On the server I have already allowed everything I believe I need:

{"Access-Control-Allow-Origin", "*"},
{"Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS"},
{"Access-Control-Allow-Headers", "X-PINGOTHER,X-Requested-With,Accept,Content-Type"}

[ServiceContract]
public interface IPlatform
{
    [OperationContract]
    [WebInvoke(UriTemplate = "testbuyTicket")]
    TicketResponse TestBuyTicket(PurchaseRequest purchaseRequest);
}

Any help would be appreciated. I feel like I've tried everything. Thanks in adance.

回答1:

I have found a solution, I'm not sure if it's the most elegant solution but it does work.

Basically I have an endpoint that the call should be directed too, but it only accepts POST requests, so I have added an OPTIONS endpoint with an empty method and it all appears to work now.

So I now have:

[ServiceContract]
public interface IPlatform
{
    [OperationContract]
    [WebInvoke(UriTemplate = "testbuyTicket")]
    TicketResponse TestBuyTicket(PurchaseRequest purchaseRequest);

    [OperationContract]
    [WebInvoke(UriTemplate = "testbuyTicket", Method = "OPTIONS")]
    TicketResponse TestBuyTicketOptions(PurchaseRequest purchaseRequest);
}

Doing this allows the server to respond to the OPTIONS call and then the POST call.

Thanks everyone for your assistance.

Big shoutout to @demas for the idea, see post Response for preflight has invalid HTTP status code 405 for more info



回答2:

Like @charlietfl says, this doesn't appear to be a CORS issue, since you seem to be returning the headers OK (per the screenshot).

My guess is that your web server (Apache or whatever) doesn't allow OPTIONS requests - many only allow GET/POST/HEAD by default.

Probably a simple web server setting...