2017-06-02 149 views
-1

我一直在使用角模板制作node.js网站。 但我无法在DB(Mongo)上创建数据。 这里是代码。401邮政未经授权的回复

节点路由。

var Property = mongoose.model('Property'); 
var jwt = require('express-jwt'); 
var auth = jwt({ 
    secret: 'SECRET', 
    userProperty: 'payload' 
}); 
var Schema = mongoose.Schema; 
var ObjectId = Schema.ObjectId; //Have also tried Schema.Types.ObjectId, mongoose.ObjectId 

// Property Routing Management 

router.post('/property', auth, function(req, res, next) { 
    var property = new Property(req.body); 
    console.log("checkpoint api"); 
    property.save(function(err, property) { 
    if (err) { 
     return next(err); 
    } 
    return res.json(property); 
    }) 
}); 

AngularJS HTML

<form class="form-horizontal"> 

    <label class="col-md-3 control-label" for="title">Member Name:</label> 
    <div class="col-md-5"> 
    <input id="notific8_text" type="text" class="form-control" value="" placeholder="" ng-model="property.user"> 
    </div> 
    <button ng-click="updateProperty()"> Submit </button> 
</form> 

AngularJS控制器。

angular.module('MainApp').controller('EditPropertyController', [ 
     '$scope',   
     's_property', 
     's_auth', 
     '$state', 
     '$location', 
     function($scope, s_property, s_auth, $state, $location) { 
    $scope.updateProperty = function() 
    { 
     var data = { 
      user: $scope.property.user,    
     } 
     s_property.create(data); 
    }; 
}]); 

和AngularJS服务。

angular.module('MetronicApp') 
    .factory('s_property', [ 
    '$http', 
    '$window', 
    's_auth', 
    function($http, $window, s_auth) { 
     var service = { 
     all_properties: [], 
     current_property: {} 
     }; 

     service.create = function(property) { 
     console.log("checkpoint service"); 
     return $http.post('/api/v1/property', property); 
     }; 
    }; 
    ]); 

当我在输入标签的输入数据,然后点击提交按钮,镀铬控制台这样表示

POST http://localhost:3000/property 401 (Unauthorized) 

什么是错? 干杯。

PS

这是

angular.module('MainApp') 
 
.factory('s_auth', ['$http', '$window', function($http, $window){ 
 
\t var auth = {}; 
 

 
\t auth.saveToken = function (token) { 
 
\t \t $window.localStorage['current-user-token'] = token; 
 
\t }; 
 

 
\t auth.getToken = function() { 
 
\t \t return $window.localStorage['current-user-token']; 
 
\t }; 
 
}

服务

+1

应该不是'/ api/v1/property'吗?似乎你有一些东西与你没有告诉我们的路线混淆。 –

+0

您的后端需要JWT,但您并未在请求中添加任何“授权”标头。使“401 **未授权**”的回应显而易见,你不觉得吗? – Phil

+0

你好,尼尔,谢谢你的回答。这是我的打字错误。控制台显示POST http:// localhost:3000/api/v1/property 401(未授权)。干杯。 –

回答

0

看起来你是不是送JWT令牌后端。 要发送它尝试在您的发布请求中添加headers { authorization: "{TOKEN}"}