我接管了一个独立的前端和后端网站,由RubyonRails和React两个后端组成。在此之前,我一直使用MVC框架来制作网站,但现在的"V";部分已独立成为React回购。
具体来说,我必须在Controller#Action中编写一个render json: @variable
,但在这之后,我不知道json在哪里传输到前端(React repo(?我不知道如何找到API端点。
我听说这和React路线有关?这是什么?这是在哪里写的?
问题很大,如果你有推荐的教学文章,请告诉我。
如果您将Rails作为后端,将React作为前端,则需要从React调用Rails API。您需要从Rails方法返回json,您也可以在方法中声明格式,所以如果格式类型是json,则返回json-elset-return html。您可以检查confi/routes以了解方法的路径。若要检查rails API调用是否有效以及数据是如何返回的,可以使用poster。一旦用http方法(get、put、post等(和参数在poster中测试了相同的api,就可以在React中作为api传递。
示例
区块报价
loadTdlists() {
axios
.get("users/user_list.json")
.then((res) => {
this.setState({ tdlists: res.data });
})
.catch((error) => console.log(error));
}
区块报价
这里的user_list方法是在users控制器中定义的。根据项目要求,在调用api时也可以使用完整的URL。
我是rails的初学者,我在前端启动了rails-api+react.native项目。我在一个命令中找到了到前端的端点。
rails routes
它向我们展示了一些数据,如:
new_api_user_session GET /api/v1/auth/sign_in(.:format) devise_token_auth/sessions#new
api_user_session POST /api/v1/auth/sign_in(.:format) devise_token_auth/sessions#create
destroy_api_user_session DELETE /api/v1/auth/sign_out(.:format) devise_token_auth/sessions#destroy
new_api_user_password GET /api/v1/auth/password/new(.:format) devise_token_auth/passwords#new
edit_api_user_password GET /api/v1/auth/password/edit(.:format) devise_token_auth/passwords#edit
api_user_password PATCH /api/v1/auth/password(.:format) devise_token_auth/passwords#update
PUT /api/v1/auth/password(.:format) devise_token_auth/passwords#update
POST /api/v1/auth/password(.:format) devise_token_auth/passwords#create
cancel_api_user_registration GET /api/v1/auth/cancel(.:format) devise_token_auth/registrations#cancel
new_api_user_registration GET /api/v1/auth/sign_up(.:format) devise_token_auth/registrations#new
edit_api_user_registration GET /api/v1/auth/edit(.:format) devise_token_auth/registrations#edit
api_user_registration PATCH /api/v1/auth(.:format) devise_token_auth/registrations#update
PUT /api/v1/auth(.:format) devise_token_auth/registrations#update
DELETE /api/v1/auth(.:format) devise_token_auth/registrations#destroy
POST /api/v1/auth(.:format) devise_token_auth/registrations#create
new_api_user_confirmation GET /api/v1/auth/confirmation/new(.:format) devise_token_auth/confirmations#new
api_user_confirmation GET /api/v1/auth/confirmation(.:format) devise_token_auth/confirmations#show
POST /api/v1/auth/confirmation(.:format) devise_token_auth/confirmations#create
api_v1_auth_validate_token GET /api/v1/auth/validate_token(.:format) devise_token_auth/token_validations#validate_token
例如CCD_ 2是注册用户的端点。我把它交给了前端开发人员,效果很好。如果你想测试你的端点,你可以使用Insomnia或Postman这样的程序,里面有json数据