简体   繁体   中英

Angular.js 401 Unauthorized Status Code

I want to get access token for authentication. My post result like

POST https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token 401 (Unauthorized)

but when I try to post with postman it works.

Server Side Headers

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.header('Content-Type', 'application/json');

Angular Code

Service

function signIn(data) {

    var deferred = $q.defer();


    $http.post('https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token', data,
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
    )
        .success(function (response, status, headers, config) {
            deferred.resolve(response);
        }).error(function () {
            deferred.reject("Failed to login");
        });

    return deferred.promise;

}

controller

  vm.loginData = {

    'client_id': 'client',
    'client_secret': 'client',
    'grant_type': 'password',
    'username': '',
    'password': ''
};


vm.login = function login() {

    loginService.signIn(vm.loginData).then(function (result) {
            vm.signInResult = result;

        },
        function (data) {

        });


}

邮递员结果

POST https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token 401 (Unauthorized)

Here is suggestions to solve your problem;

Use cors module (not required);

Server Side

I assume that your passport code working properly.

var cors= require('cors');

//init first.

app.options(cors({origin'*'}));  //Use your origins.
app.use(cors({origin'*'}));      //Use your origins.

Client Side

Just delete headers options

//...

$http.post('https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token', data)
    .success(function (response, status, headers, config) {
        deferred.resolve(response);
    }).error(function () {
        deferred.reject("Failed to login");
    });
//...

If one POST works and the other doesn't, then your angularjs $http request is making the request with the wrong parameters.

I'd suggest you to get an http analyser (like Fiddler) and compare the actual request done by Postman vs the request done by you angular app.

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