ruby-on-rails - 为什么我对 Rails 后端的调用导致我的 React 获取 public/index.html 文件?
问题描述
我一直在关注一个教程(https://github.com/fullstackreact/food-lookup-demo-rails)来设置一个反应前端和rails后端。本教程本身运行良好。但是,当我偏离并尝试一些我自己的代码时,事情根本就没有解决。我的偏差是我使用了不同的控制器和模型。但是,我已经复制了教程中的所有其他内容。
当我从本地 rails api 获取时,我会取回位于 react 文件夹中的 public/index.html 文件。当我获取随机 api 时,例如:
https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty
然后正确使用api并且它是json。
当我通过访问 localhost:3000/api/stories 查询后端时,我得到一个 json 输出。
下面是 React 的 App.js 文件
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
componentDidMount() {
fetch("/api/stories")
// .then(response => response.json())
.then(res => res.json())
.then(json => console.log(json))
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
这是故事 api 的控制器
class StoriesController < ApplicationController
def index
@stories = Story.limit(2)
render(
status: 200,
json: @stories.to_json
)
end
end
以下是package.json,表明我正确设置了代理路由:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-scripts": "3.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
"proxy": "http://localhost:3001/"
}
}
谢谢你的任何见解
解决方案
根据您提供的教程,您应该将 API 服务器托管在 localhost:3001。您可以查看自述文件以获取更多信息。
推荐阅读
- android - 如何获取 OkHttp 4.x 的 UserAgent?
- javascript - 将一个 json 对象附加到另一个 json 对象中的最后一个 Array
- python - 我不明白我曾经 Glob 多种文件类型的 Python 解决方案
- reactjs - 如何使用 React 和 Typescript 在 useEffect 挂钩中设置状态?
- python - 通过 Microsoft Graph 自动发送电子邮件
- python - heroku pip requirements.txt google-cloud-speech 失败
- plupload - 如何限制 PLUpload 中的总文件大小
- c - 如何检查 char* 在 C 中是否只有十六进制字符?
- android - firebase FCM包的真实名称是什么
- typescript - 尽管更改了 package.json 和 tsconfig.json,但无法在 TypeScript 中的模块外导入语句