【问题标题】:401 Unauthorized Response On Post401 未经授权的帖子回复
【发布时间】:2017-11-03 14:15:42
【问题描述】:

我一直在使用 Angular 模板制作 node.js 网站。 但我无法在 DB(Mongo) 上创建数据。 这是代码。

节点路由。

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);
      };
    };
  ]);

当我在输入标签中输入数据并单击提交按钮时,chrome控制台显示如下

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

什么是错误? 干杯。

PS

这是

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

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

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

服务

【问题讨论】:

  • 不应该是/api/v1/property吗?似乎你有什么东西弄乱了你没有告诉我们的路线。
  • 您的后端需要 JWT,但您没有在请求中添加任何 Authorization 标头。让“401 Unauthorized”响应很明显,你不觉得吗?
  • 您好,尼尔,感谢您的回答。这是我的打字错误。控制台显示 POST localhost:3000/api/v1/property 401(未经授权)。干杯。
  • 建立不记名令牌通常需要几个授权请求。你这是在哪里做的? s_auth.getToken() 是如何填充令牌的?
  • 嗨菲尔,我已经更新了我的问题。

标签: javascript angularjs node.js express


【解决方案1】:

您似乎没有将 JWT 令牌发送到您的后端。 要发送它,请尝试在您的帖子请求中添加headers { authorization: "{TOKEN}"}

【讨论】:

    猜你喜欢
    • 2011-12-12
    • 2023-03-09
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    相关资源
    最近更新 更多