401 Unauthorized Response On Post

柔情痞子 提交于 2020-02-25 23:37:32

问题


I've been making node.js website using angular template. But I can't create data on DB(Mongo). Here are code.

node routing.

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 Controller.

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

and AngularJS service.

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

When I input data in the input tag and click the submit button, chrome console shows like this

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

What is the mistake? Cheers.

PS

this is

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

service


回答1:


Looks like you are not sending the JWT token to your backend. TO be sending it try adding headers { authorization: "{TOKEN}"} in your post request



来源:https://stackoverflow.com/questions/44319321/401-unauthorized-response-on-post

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