Ajax调用不再有效(401未授权)

时间:2017-10-13 14:08:56

标签: javascript ruby-on-rails

下面的代码在我的分支上完美运行(甚至之前的一些提交)并且神秘地我现在收到js消息: 401(未经授权)在我检查浏览器之后。

我有一个自动填充表单,当用户选择一个字段时,它需要发送此数据以通过同一控制器中的操作“get_location”进行分析。

home_form.js

$(document).ready(function() {
  return $("#search_city").on("change", function() {
    return $.ajax({
      url: "home/get_location",
      type: "GET",
      dataType: "script",
      data: {
        city: $('#search_city').val()
      }
    });
  });

的routes.rb

  resources :home, only: [:index] do
    get 'get_location', on: :collection
  end

home_controller.rb

require 'recognize_data'

class HomeController < ApplicationController
  layout "home"
  skip_before_action :authenticate_user!, only: [ :index ]
  include DataX

  def index
  end

  def get_location
    # do some stuff here
  end

end

home.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <%= csrf_meta_tags %>
    <%= action_cable_meta_tag %>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <%= stylesheet_link_tag 'home/manifest.css', media: 'all' %>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5LELGIW21xr6W1H1NBQNvjqLM3hENa64&libraries=places&language=pt-BR"></script>
    <%= javascript_include_tag 'home/manifest.js' %>
  </head>

<body>

<%= yield %>

<%= yield(:form_js) %>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我的代码存在两个问题:

1-是的,我忘了把最后一个});关闭js功能

$(document).ready(function() {
  return $("#search_city").on("change", function() {
    return $.ajax({
      url: "home/get_location",
      type: "GET",
      dataType: "script",
      data: {
        city: $('#search_city').val()
      }
    });
  });
});

2 - 我在home_controller上使用了skip_before_action :authenticate_user!, only: [:index],它导致了与get_location操作的冲突。所以我从索引中删除了限制,只留下句子:skip_before_action :authenticate_user!以涵盖所有操作。