сервер ответил со статусом 404 (не найден) - PullRequest
0 голосов
/ 18 января 2019

Я пытаюсь переделать мое приложение реагирующих рельсов с помощью gresql, чтобы я мог развернуть его с помощью heroku. Пока что все работает нормально, кроме запроса POST. Я получаю сообщение об ошибке 404 (не найдено), и в моем терминале не отображается связывание.pry, поэтому я не вижу из контроллера.

Я думаю, что это может иметь какое-то отношение к тому, как он отправляет обратно json с помощью render: json. Прежде чем я использовал response_to do | format | format.json {.

import fetch from 'isomorphic-fetch';

export function saveData(rec) {
  debugger
  return function(dispatch){
    return fetch(`/api/v1/charts`, {
      credentials: "include",
      method: "POST",
      headers: {
        'Accept': "application/json",
        'Content-Type': "application/json",
      },
      body: JSON.stringify(rec)
    })
    .then(res => {
      return res.json()
    }).then(data => {
         debugger
         dispatch({type: 'ADD_CHART', payload: data})
    })
  }
}

module Api::V1
  class ChartsController < ApplicationController

      def index
          @charts = Chart.all
          render json: @charts, include: ["people", "weights"]
      end

      def create
          binding.pry
          @chart = Chart.create(chart_params)
          render json: @chart, include: ["people", "weights"]
      end

      def destroy
          Chart.find(params[:id]).destroy
      end

      private

      def chart_params
          params.require(:chart).permit(:id, :date, people_attributes: [:name, weights_attributes: [:pounds, :currentDate] ])
      end
  end
end

module Api::V1
  class PersonsController < ApplicationController

    def index
      @persons = Person.all
      render json: @persons, include: "weights"
    end

    def create
        binding.pry
        @person = Person.create(person_params)
        render json: @person, include: "weights"
    end

    private

    def person_params
      params.require(:person).permit(:id, :name, weights_attributes: [:pounds, :currentDate])
    end
  end
end

module Api::V1
  class WeightsController < ApplicationController

      def index
         @weights = Weight.all
         render json: @weights
      end

      def create
         binding.pry
         e = Weight.where(:person_id => params[:person_id], :currentDate => params[:currentDate])
          if !e.empty?
            e.first.pounds = params[:pounds]
            e.first.save!
            @weight = e
          else
            @weight = Weight.create(weight_params)
          end

          render json: @weight
      end

      private

      def weight_params
        params.require(:weight).permit(:id, :pounds, :currentDate, :person_id)
      end
  end
end

class ApplicationController < ActionController::API
end

Ответы [ 2 ]

0 голосов
/ 18 января 2019

Изменение моей выборки на полный URL-адрес и удаление учетных данных: «include» работал

импортировать выборку из 'isomorphic-fetch';

export function saveData(rec) {
  debugger
  return function(dispatch){
    var url = 'http://localhost:3001/api/v1/charts';
    return fetch(url, {
      method: "POST",
      headers: {
        'Accept': "application/json",
        'Content-Type': "application/json",
      },
      body: JSON.stringify(rec)
    })
    .then(res => {
      return res.json()
    }).then(data => {
         debugger
         dispatch({type: 'ADD_CHART', payload: data})
    })
  }
}
0 голосов
/ 18 января 2019

Если вы объявили маршруты ресурсов для вашего charts, вам нужно изменить эту строку:

return fetch(`/api/v1/charts`, {

на: return fetch( / api / v1 / chart , {

Как есть, charts, вероятно, вызывает POST к вашему действию индекса.

...