SyntaxError: Unexpected token < in JSON at position 0 - React app in Rails API

SyntaxError: Unexpected token < in JSON at position 0 - React app in Rails API

我正在 Rails 5.0.6 作为 API 工作。我还在节点服务器版本 v9.8.0 上 运行 为前端 运行 宁一个 React 应用程序。在 localhost:3000 上 运行ning 的 React 应用程序上,我收到以下错误:

rails 用作 API 所以在控制器中我 return @drinks 格式为 json。

drinks_controller.rb

class DrinksController < ApiController
  # GET /drinks
  def index
    @drinks = Drink.select("id,title").all

    render json: @drinks.to_json
  end

  # GET /drinks/1
  def show
    @drink = Drink.find(params[:id])
    render json: @drink.to_json(:include => { :ingredients => { :only => [:id, :description] }})
  end
end

我 运行 两台服务器都在本地使用 Procfile in Profile.dev

web: cd client && PORT=3000 npm start
api: PORT=3001 && bundle exec rails s

当我在 localhost:3001/api/drinks 上 运行 访问 rails 服务器时,我得到以下信息:

[{"id":1,"title":"Sparkling Negroni"},{"id":2,"title":"Pineapple-Jalapeño Margarita"}]

采用 json 格式,在 app.js 即时消息从该端点

获取
class App extends Component {
  componentDidMount() {
    window.fetch('api/drinks')
      .then(response => response.json())
      .then(json => console.log(json))
      .catch(error => console.log(error))
  }

是代理不工作吗?

{
  "name": "package-json",
  "version": "4.0.1",
  "description": "Get metadata of a package from the npm registry",
  "license": "MIT",
  "repository": "sindresorhus/package-json",
  "proxy": "http://localhost:3001",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  }

我不明白这是什么问题?

我怀疑你的 rails 应用返回 html 而 fetch 期望 JSON... < 字符表示 HTML 字符串正在交付,(JSON 解析器在 HTML 上阻塞)。

尝试转储响应 "as is" 以查看您收到的内容。

class App extends Component {
  componentDidMount() {
    window.fetch('api/drinks')
      .then(response => {
         console.log(response.status);
         console.log(response.body);
         return response.json();
      })
      .then(json => console.log(json))
      .catch(error => console.log(error))
}