Ajax请求与Rails 5应用程序获取错误401(未授权)

问题描述:

我有一个rails 5应用程序,我只是试图实现一个像按钮功能。在我的情况下,我在做upvotes。当登录用户点击按钮时,它应该增加1.我为用户和管理员使用设计。Ajax请求与Rails 5应用程序获取错误401(未授权)

我show.html.erb

<% if member_signed_in? %> 
<div class"movie-votes"> 
    <medium id="votes"><%= @movie.votes %> members like this film</medium> 
    <button id="upvote" type="submit">I Like this Film</button> 
</div> 

我的Ajax请求

"use strict"; 
console.log("loaded"); 
$(document).ready(function(){ 

var member = $("member"); 
var password = $("password"); 
$("#upvote").click(function() { 
console.log("clicked"); 
var id = $(this).data("id"); 

$.ajax({ 
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(member + ":" + password)); }, 
    url: "/movies/votes", 
    type: "POST", 
    data: { 
    member: "[email protected]", 
    password: "password", 
    id: id, 
votes: true 
    }, 
    success: function() { 
    var vote_counter = $("#votes"); 
    // console.log(vote_counter); 
    var current_vote = parseInt($("#votes").html()); 
    vote_counter.html(current_vote + 1); 
    alert(vote_counter); 
    } 
    }) 
}) 
}) 

MoviesController

before_action :set_movies, only: [:show, :edit, :destroy, :update, :votes] 

def votes 
@movie.update(votes: @movie.votes + 1) 
end 

private 

def set_movies 
    @movie = Movie.find(params[:id]) 
end 

的错误,当我打开了我越来越合作本地主机上的nsole。

loaded 
clicked 
jquery.self-660adc5….js?body=1:10246 POST http://localhost:3000/movies/votes 401 (Unauthorized) 

发生这种情况后,我点击“我喜欢这部电影”按钮。 Sidenote,我现在禁用了turbolinks,因为这一直是过去的问题。 如果需要,这里是我的GitHub

+0

你研究过类似的问题吗? – Nithin

+0

发布'投票'行动的整个代码将比仅仅几行有更多的帮助。这是添加投票功能的非常不安全的方式。你也应该检查一下,这个用户是否已经投了票。 – Abhinay

+0

投票动作渲染的反应是什么? –

很明显,这个问题是由于认证。除了认证,你仍然有几个问题在你的代码,如

  • 你是不是传递movievotes行动id

  • 你的控制器假定params[:id]在那里,因此试图找到电影,但它无法得到它。

在你html代码,在button标签添加数据属性:

<% if member_signed_in? %> 
<div class"movie-votes"> 
    <medium id="votes"><%= @movie.votes %> members like this film</medium> 
    <button data-movie="<%= @movie.id %>" id="upvote">I Like this Film</button> 
</div> 

在你Ajax代码:

$(document).ready(function(){ 

    var member = $("member"); 
    var password = $("password"); // <-- this is the actual password you are passing here? 
    $("#upvote").click(function() { 
    var id = $(this).attr("data-movie"); 

    $.ajax({ 
    beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(member + ":" + password)); }, 
     url: "/movies/votes", 
     type: "POST", 
     data: { 
     member: "[email protected]", 
     password: "password", 
     id: id, 
     votes: true 
     }, 
     success: function() { 
     var vote_counter = $("#votes"); 
     // console.log(vote_counter); 
     var current_vote = parseInt($("#votes").html()); 
     vote_counter.html(current_vote + 1); 
     alert(vote_counter); 
     } 
    }); 
    }); 
}); 

PS:我不知道,如果它是一个正确的建立投票功能的方式。我建议使用像act_as_votable这样的宝石,它会更整洁。