2015-06-19 15 views
0

我在Rails 4.2 API(針對Angular前端)中構建了一個博客。我用設計添加了用戶(我知道矯枉過正),並且我的控制器測試通過了一切。當我嘗試使用curl POST請求或嘗試從我的Angular應用創建用戶時,我得到一個406不可接受的狀態碼。Rails 4 Api用戶發佈測試失敗

這裏是我創造的控制器方法:

def create 
    user = User.new(user_params) 
    if user.save 
     render json: user, status: 201 
    else 
     render json: { errors: user.errors }, status: 422 
    end 
end 

private 
def user_params 
    params.require(:user).permit(:email, :password, :password_confirmation) 
end 

我能沒有問題,以創建從鐵軌控制檯用戶。

這裏是curl命令我一直努力:

curl -i -H 'Accept: application/json' -H 'Content-type: application/json' -X POST -d '{"email":"[email protected]","password":"12345678","password_confirmation":"12345678"}' http://api.myapi.dev/users 

,我有這個資源太:

api_users POST /users(.:format)       api/users#create {:subdomain=>"api"} 

我可以更新用戶,並沒有問題,執行從捲曲的任何其他行動,我只是在這裏看不到問題。任何幫助是極大的讚賞。

回答

0

根據W3406響應是:

該請求所標識的資源僅能夠產生具有根據在請求中發送的接受報頭,內容無法接收響應實體。

所以當你使用cURL時,你不需要發送-H 'Accept: application/json' -H 'Content-type: application/json,Rails會自動爲你呈現JSON結果。因爲您只在控制器中指定了format.json

Rails的希望您能在以下方式發送數據:

{ "users": { "email", "[email protected]" }, ... } 

當你不發送users當你點擊使用curl命令的服務器。

+0

謝謝,但沒有奏效。在其他POST調用上移除標題也不起作用。我想我需要他們。 – baron816

+0

@ baron816我編輯了我的答案。請檢查一下。 –

+0

謝謝,我現在明白了。是的,它需要{「用戶」:{...}}。我想我還需要在ApplicationController中添加 DeviseController.respond_to:json 。它似乎仍然需要標題。 – baron816