【问题标题】:Vuejs Axios RequestVuejs Axios 请求
【发布时间】:2020-06-21 03:11:27
【问题描述】:

前端

 data() {
    return {
      user_data: [],
      user_id: '',
    };
  },
created() {
    this.getUserData();
    const decode = jwtDecode(localStorage.auth_token);
    this.user_id = decode.user_id;
  },
methods: {
getUserData() {
      axios.get(`http://localhost:3000/api/v1/users/${this.user_id}`) // Gets an specif book
        .then((response) => {
          this.user_data = response.data;
        });
    },
}

后台展示方式

def show
 user = User.find(params[:id])
   render json: user
 end

路线

api_v1_user GET    /api/v1/users/:id(.:format) 

在上面的代码中,我从我的令牌中获取用户 ID,并在我的方法 getUserData() 中从数据库中获取他的信息。但是,当我提出请求时,它没有带上特定的用户,而是给了我所有的注册用户。 P.s:我尝试在我的getUserData 方法中打印用户ID,以查看该ID 是否在变量user_id 中并且它工作正常,但我的请求无法得到它! 有人能帮我吗?

【问题讨论】:

  • 问题出在后端代码,你应该分享控制器的代码
  • 你能显示你的获取请求处理程序吗?
  • 什么意思?

标签: ruby-on-rails vue.js axios


【解决方案1】:

在上面的代码中,我从我的令牌中获取用户 ID,并在我的方法 getUserData() 中从数据库中获取他的信息

代码中的顺序相反,它向http://localhost:3000/api/v1/users/发出请求,没有用户ID。

相反,它应该是:

const decode = jwtDecode(localStorage.auth_token);
this.user_id = decode.user_id;
this.getUserData();

如果有可能没有用户 ID,则不应调用 getUserData

【讨论】: