我接手了一個獨立的前端和后端網站,由兩個后端組成,Ruby on Rails 和 React。在此之前,我一直使用MVC框架來制作網站,但現在“V”部分已經獨立成為一個React repo。
具體來說,我必須render json: @variable在Controller#Action中寫一個,但是在此之后我不知道json從哪里傳輸到前端(React repo)?我不知道如何找到 API 端點。
聽說這和 React 路由有關?這是什么?這是哪里寫的?
問題很大,如果有推薦的教學文章請告訴我。
uj5u.com熱心網友回復:
如果您將 Rails 作為后端,將 React 作為前端,則需要從 React 呼叫 Rails API。您需要從 Rails 方法回傳 json,您也可以在方法中宣告格式,因此如果格式型別為 json,則回傳為 json,否則回傳 html。您可以檢查 confi/routes 以了解方法的路徑。要檢查 rails API 呼叫是否有效以及資料如何回傳,您可以使用郵遞員。使用 http 方法(get、put、post 等)在 postman 相同的 api 中測驗后,引數可以在 React 中作為 API 傳遞。
例子
塊參考
loadTdlists() {
axios
.get("users/user_list.json")
.then((res) => {
this.setState({ tdlists: res.data });
})
.catch((error) => console.log(error));
}
塊參考
這里 user_list 方法是在用戶控制器中定義的。您也可以根據專案要求在呼叫 api 時使用完整的 URL。
uj5u.com熱心網友回復:
我是 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
例如/api/v1/auth/sign_in是注冊用戶的端點。我把它交給了前端開發人員并且運行良好。如果你想測驗你的端點,你可以使用像 Insomnia 或 Postman 這樣的程式,其中包含 json 資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/394833.html
上一篇:Rails7-帶有方法的link_to:delete仍然執行GET請求
下一篇:如何判斷一個關系是否剛剛被洗掉?
