【问题标题】:SyntaxError: Unexpected token o in JSON at position 1 when get rails jsonSyntaxError:获取rails json时JSON中位置1的意外标记o
【发布时间】:2019-01-02 15:44:44
【问题描述】:

您好,当我尝试在我的 rails 应用程序中搜索(不是 api 模式)时,我使用 rails 5、webpacker 和 vue

在我的控制器中这是我的代码

def search_information_sources
 text = params[:text]
 @list_books = Book.where('title ILIKE ?', "#{text}%").limit(10)
 render json: @list_books
end

在我的 vue 组件中,我调用了 promise

    const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    axios.get("/syllabuses/search_information_sources", {
      authenticity_token: token,
      text: "negocios"
    })
    .then(function (response) {
      console.log(response.data);
      this.items_basic = JSON.parse(response.data);
    })
    .catch(function (error) {
      alert(error);
      toastr.error("No se pudo procesar la solicitud,  " + error.response.data.message_error);
    });  

但是当我执行此代码时,我收到错误

这是我在 Rails 中的日志

Started GET "/syllabuses/search_information_sources.json" for ::1 at 2019-01-02 11:03:00 -0500
11:03:00 backend.1  | Processing by SyllabusesController#search_information_sources as JSON
11:03:00 backend.1  |   User Load (3.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
11:03:00 backend.1  |   ↳ app/controllers/application_controller.rb:32
11:03:00 backend.1  |   Book Load (1.0ms)  SELECT  "books".* FROM "books" WHERE (title ILIKE '%') LIMIT $1  [["LIMIT", 10]]
11:03:00 backend.1  |   ↳ app/controllers/syllabuses_controller.rb:143
11:03:00 backend.1  | Completed 200 OK in 48ms (Views: 16.8ms | ActiveRecord: 4.6ms)

【问题讨论】:

  • 你在哪里得到这个错误?,它发生在你的控制器中吗?或在您的 javascript 代码中?它似乎发生在您的控制器中,如果是这样,您介意发布您的请求/响应的 Rails 日志吗?您的控制器中是否有 before_filters 运行?。
  • 嗨芬达,我在我的回答中添加了我的日志。当我使用 alert(error) 打印错误捕获时收到的错误我没有此操作的 before_filter..
  • 所以看起来你的控制器代码没问题。在then 函数之前的console.log 之前放置一个debugger,看看你得到了什么,尝试手动执行JSON.parse(response.data) 行,看看是否会导致错误。
  • 我认为你不必使用JSON.parse。来自 axios 文档:JSON responses are automatically parsed.

标签: ruby-on-rails json webpack vuejs2 axios


【解决方案1】:

我解决了这个问题,问题是上下文

var _that = this;

我使用 var _that = this;在调用 de promise 之前然后在里面我使用

_that.items_basic =response.data;

我的 javascript 的最终代码是

var _that = this;
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
let resultado = [];
axios.get("/syllabuses/search_information_sources.json", {
  authenticity_token: token,
  params: {text_filter: text}
})
.then(function (response) {
  console.log(response.data);
  _that.items_basic = response.data;
})
.catch(function (error) {
  alert(error);
  toastr.error("No se pudo procesar la solicitud,  " + error.response.data.message_error);
});

【讨论】:

    猜你喜欢
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多