http put请求导致" net :: ERR_TOO_MANY_REDIRECTS"错误

时间:2016-04-20 07:18:55

标签: ruby-on-rails angularjs json http request

我有一个Angular客户端向rails后端发出http put请求。

http请求代码如下:

    $http({
        method: 'PUT',
        url: 'http://localhost:3000/documents/' + $scope.document_id,
        data: parameter
    }).then(function successCallback(response) {
            console.log(response);
        }, function errorCallback(response) {
            console.log("Error has occurred while getting user document data from the server");
        });

我传递的数据如下,它是一个有效的JSON:

        var parameter = {
  "document": {
    "title": "I-129",
    "data": JSON.stringify($scope.formData),
    "user_id": 1
  }
}

后端代码就像下面这样:

  def update
    respond_to do |format|
      if @document.update(document_params)
        format.html { redirect_to @document, notice: 'Document was successfully updated.' }
        format.json { render :show, status: :ok, location: @document }
      else
        format.html { render :edit }
        format.json { render json: @document.errors, status: :unprocessable_entity }
      end
    end
  end

服务器日志我得到:

Started PUT "/documents/3" for ::1 at 2016-04-20 00:24:12 -0700
Processing by DocumentsController#update as HTML
  Parameters: {"document"=>{"title"=>"I-129", "data"=>"{\"text_id\":\"1111\",\"Date_id\":\"1111-11-11T08:00:00.000Z\",\"number_id\":11111222}", "user_id"=>0}, "id"=>"3"}
Can't verify CSRF token authenticity
  Document Load (0.1ms)  SELECT  "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1  [["id", 3]]
   (0.0ms)  begin transaction
  Document Exists (0.1ms)  SELECT  1 AS one FROM "documents" WHERE ("documents"."title" = 'I-129' AND "documents"."id" != 3) LIMIT 1
   (0.0ms)  commit transaction
Redirected to http://localhost:3000/documents/3
Completed 302 Found in 3ms (ActiveRecord: 0.3ms)

每当我发出put请求时,我都会收到错误

  

http://localhost:3000/documents/3 net :: ERR_TOO_MANY_REDIRECTS

我在这里做错了什么?我确认我可以通过URL('http://localhost:3000/documents/' + $scope.document_id)通过Paw(与Postman类似的程序)执行http put请求。

1 个答案:

答案 0 :(得分:2)

从日志中可以看到rails将呼叫视为HTML

Processing by DocumentsController#update as HTML

尝试将此添加到http调用

 dataType: "json",
 headers: {
     "Content-Type": 'application/json; charset=UTF-8',
     "Accept" : "application/json"
 }