简体   繁体   中英

Only part of the response is retrieved at the ionic 4 front-end

I am sending an http GET request from ionic to a NodeJS server using tokens. I get a message that data has been successfully retrieved. However, the data property of the response is not sent to the frontend and is assigned to undefined when i try to log it in the console. Here is the code for my ionic request:

 getPoints() {
    var headers = new Headers();
    headers.append("Authorization", "Bearer " + this.getAuthorizationToken());
    headers.append("Content-Type", "application/json");
    console.log(this.getAuthorizationToken());
   return this.http
      .get(environment.apiUrl + "/user/getCurrentPoints", {
        headers
      })
      .map(res => res.json());
  }

This is the code inside an ionic component where I am calling the GET method in the constructor:

 constructor(
    ease: RoundProgressEase,
    private _router: Router,
    private formB: FormBuilder,
    private _authService: AuthService
  ) {
    for (let prop in ease) {
      if (prop.toLowerCase().indexOf("ease") > -1) {
        this.animations.push(prop);
      }
    }
    this._authService.getPoints().subscribe((res: any) => {
      console.log("data points", res);
    });
  }

Also here is the endpoint at the backend:

    router.get(
      "/user/getCurrentPoints",
      isAuthenticated,
      userCtrl.getCurrentPoints
    );

Here is the middleware isAuthenticated:

  var isAuthenticated = function(req, res, next) {
      var token = req.headers["authorization"];
      console.log(req.header);
      token = req.headers.authorization.split("Bearer ")[1];
      if (!token) {
        return res.status(401).json({
          error: null,
          msg: "You have to login first before you can access your lists.",
          data: null
        });
      }
      jwt.verify(token, req.app.get("secret"), function(err, decodedToken) {
        if (err) {
          return res.status(401).json({
            error: err,
            msg: "Login timed out, please login again.",
            data: null
          });
        }
        req.decodedToken = decodedToken;
        console.log(req.decodedToken);
        next();
      });
    };

Finally, this is the userCtrl.getCurrentPoints controller method:

module.exports.getCurrentPoints = function(req, res, next) {
  console.log("accessed get current points");
  if (!Validations.isString(req.decodedToken.user.username)) {
    return res.status(422).json({
      err: null,
      msg: "type parameter must be a valid String.",
      data: null
    });
  }
  User.find({ username: req.decodedToken.user.username }).exec(function(
    err,
    user
  ) {
    if (err) {

      return next(err);
    }
    res.status(200).json({
      err: null,
      msg: "Current user points retrieved successfully.",
      data: user.points
    });
  });
};

This is the response i get

{err: null, msg: "Current user points retrieved successfully."}

The user schema

const mongoose = require('mongoose');
var Voucher = mongoose.Schema.Types.Voucher;

const userSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
    trim: true,
    lowercase: true

  },
  password: {
    type: String,
    required: true,
    trim: true
  },
  name: {
    type: String,
    required: true,
    trim: true
  },
  region: {
    type: String,
    required: true,
    trim: true,
  },
  building: {
    type: Number,
    required: true,
    min: 0
  },
  points: {
    type: Number,
    required: false,
    min: 0
  },
  vouchers: {
    type: [Voucher],
    status:[String],
    required: false,
  },

  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: Date
});

mongoose.model('User', userSchema);

What you get from backend? err or data? First check that your request gets the backend api. Second I saw that you checked for lower-case authorization in middle ware; maybe that's where things go wrong. Third maybe the user has no points at all and by default the null field is eliminated from the response.

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