在做同样的事情时,我采取了与 Jimmy 不同的方法。
我在 Heroku 上部署了两个应用程序:一个 Rails API 和一个 Create-React-App 前端。无需太具体,有几个键可以设置它。首先,在您的 rails api 中,编辑 cors.rb 文件,使其允许跨域请求:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'localhost:3000', 'https://myapp.herokuapp.com'
resource '*',
headers: :any,
methods: [:get, :post, :put, :delete],
end
end
正如这个文件所暗示的,我的 rails 应用程序没有在本地运行 localhost:3000,我通过编辑 puma.rb 将其更改为在端口 8000 上运行:
port ENV.fetch("PORT") { 8000 }
Create-react-app 默认在本地 localhost:3000 上运行,因此您可以将 rails api 设置为在您想要的任何端口上运行,只要它与您的前端不同。
然后我在我的 create-react-app 中创建了一个文件,其中包含 API url 和我称之为 AppConstants.js 的常用端点:
// let APIRoot = "http://localhost:8000";
let APIRoot = "https://my-rails-api.herokuapp.com";
export default {
APIEndpoints: {
LOGIN: APIRoot + "/users/login",
SIGNUP: APIRoot + "/users/create",
TODOS: APIRoot + "/todos",
ITEMS: APIRoot + "/items",
},
};
现在您编辑您的 fetch/ajax/xmlHttpRequest 调用,以便它使用的 URL 引用这些路由。例如使用 fetch:
fetch(AppConstants.TODOS, {
method: 'POST',
body: JSON.stringify(values)
})
.then(response => response.text())
.then((body) => {
console.log(body);
});
此应用程序常量文件可以轻松地在本地 api 根目录和生产 api 根目录之间切换。
像往常一样将您的 rails api 部署到 heroku,将自动检测到合适的构建包。对于您的 React 应用程序,我建议使用 this buildpack 来构建您的 create-react-app 的生产版本并为您提供静态资产。