Angular.js 401 Unauthorized Status Code

旧城冷巷雨未停 提交于 2019-12-11 21:09:50

问题


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)


回答1:


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");
    });
//...



回答2:


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.



来源:https://stackoverflow.com/questions/31098130/angular-js-401-unauthorized-status-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!