设置完dropzone后,日志中将显示一个简单的rails api:
Processing by Api::UsersController#update as */*
21:03:10 web.1 | Parameters: {"avatar"=>[{"preview"=>"blob:http://localhost:3000/4b4f28d6-cab3-46e5-a887-912580bbca1a"}], "access_token"=>"6jaabLFdUG-7jGuC_RvH2Q", "user"=>{"avatar"=>[{"preview"=>"blob:http://localhost:3000/4b4f28d6-cab3-46e5-a887-912580bbca1a"}]}}
21:03:10 web.1 | Can't verify CSRF token authenticity
21:03:10 web.1 | User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."access_token" = ? LIMIT 1 [["access_token", "6jaabLFdUG-7jGuC_RvH2Q"]]
21:03:10 web.1 | Unpermitted parameter: avatar
21:03:10 web.1 | (0.2ms) begin transaction
21:03:10 web.1 | User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE ("users"."username" = 'teste' AND "users"."id" != 1) LIMIT 1
21:03:10 web.1 | User Exists (0.7ms) SELECT 1 AS one FROM "users" WHERE ("users"."name" = '1' AND "users"."id" != 1) LIMIT 1
21:03:10 web.1 | (0.3ms) commit transaction
21:03:10 web.1 | Rendered text template (0.1ms)
21:03:10 web.1 | Completed 200 OK in 47ms (Views: 19.0ms | ActiveRecord: 2.0ms)
但是在控制器中,头像参数是允许的,所以有人知道为什么会发生这种情况吗?
dropzone代码:
updateAvatar(file) {
const request = new Request("http:/api/users/"+ auth.getToken(), {
method: 'PUT',
headers: new Headers({
'Content-Type' : 'application/json',
'_method' : 'put',
'content-type': 'multipart/form-data'
}),
body: JSON.stringify({avatar: file})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
<Dropzone onDrop={this.updateAvatar}>
<button>Try dropping some files here.</button>
</Dropzone>
用户控制器
def update
if @user.update_attributes(user_params)
render text: "Account has been updated successfully", status: 200
else
render json: @user.errors, status: 422
end
end
def user_params
params.require(:user).permit( :avatar,:name, :email, :password, :password_confirmation)
end
答案 0 :(得分:0)
将参数列入白名单,如下所示:
params.require(:user).permit(:name, :email, :password, :password_confirmation, avatar: [:preview])
此外,Rails应用程序无法验证CSRF令牌。
在您的ApplicationController
protect_from_forgery with: :null_session
您可以从here
了解更多有关CSRF的信息。