AngularJS: $http.get 405 (Method Not Allowed)

2020-05-07 04:08发布

问题:

when I get a request from a url,like this:


    $http({
        method: 'GET',
        url:'http://mooc-lms.dev.web.nd/v0.3/users/login'
    }).success(function(data, status, headers, config) {
        //code
    });

But the error I get is:


    GET http://mooc-lms.dev.web.nd/v0.3/users/login 405 (Method Not Allowed)

However,if I change the method from "GET" to "POST",the error is:


    POST http://mooc-lms.dev.web.nd/v0.3/users/login 415 (Unsupported Media Type)

What's the problem?Is there something wrong with the url(http://mooc-lms.dev.web.nd/v0.3/users/login)? I find '"message":"Request method 'GET' not supported"' in the url.

回答1:

The reason that GET isn't working is that the server doesn't support GET for the login endpoint, which is unsurprising. The most common reason for getting an HTTP 415 response on a POST request is because the server requires you to specify a Content-Type and/or Accept in your request header.

My example below sets them to application/json, which is common, but not ubiquitous, so you'll have to check what the server requires, and what it will give you back. Given that the address contains "mooc-lms", I assume you're doing some kind of online course. It should give you that information. That documentation should also tell you what data you need to send with the data property.

$http({
    method: 'POST',
    url: 'http://mooc-lms.dev.web.nd/v0.3/users/login',
    headers: {
        'Content-Type': 'application/json', /*or whatever type is relevant */
        'Accept': 'application/json' /* ditto */
    },
    data: {
        /* You probably need to send some data if you plan to log in */
    }
})