레일: 레일의 POST 422(처리 불가능한 엔티티)경로나 컨트롤러 때문인가요?
저는 제 웹사이트에서 사용자에게 브랜드 이름을 트윗한 것에 대해 "포인트" 또는 "크레딧"을 주려고 합니다.
적절한 뷰에 대한 멋진 트위터 위젯을 가지고 있습니다.
<p><a href="https://twitter.com/share" class="twitter-share-button" data-text="Check Out This Awesome Website Yay" data-via="BrandName" data-hashtags="ProductName">Tweet</a>
<div id="credited"></div>
<script>window.twttr = (function (d, s, id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src= "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } });
}(document, "script", "twitter-wjs"));
</script>
JS는 다 써놨는데...
function creditTweet() {
$.post(
"/credit_tweet",
{},
function(result) {
var text;
if (result.status === "noop") {
text = "Thanks for sharing already!";
} else if (result.status === "ok") {
text = "5 Kredit Added";
}
$("#credited").html(text);
}
);
}
$(function() {
twttr.ready(function (twttr) {
window.twttr.events.bind('tweet', creditTweet);
});
});
여기서 문제는 컨트롤러 또는 루트(포스팅 장소)에 있습니다.POST가 거의 기능하고 있기 때문에 루트는 정상이라고 생각합니다.wikipedia의 에러에 대한 설명입니다.422 Unprocessable Entity (WebDAV; RFC 4918).요구는 형식이 좋았지만 시멘틱 오류 때문에 따를 수 없었습니다.
내 루비코드에 무슨 문제라도 있나?
class SocialKreditController < ApplicationController
TWEET_CREDIT_AMOUNT = 5
def credit_tweet
if !signed_in?
render json: { status: :error }
elsif current_user.tweet_credited
Rails.logger.info "Not crediting #{ current_user.id }"
render json: { status: :noop }
else
Rails.logger.info "Crediting #{ current_user.id }"
current_user.update_attributes tweet_credited: true
current_user.add_points TWEET_CREDIT_AMOUNT
render json: { status: :ok }
end
end
end
그리고 제 경로에서는, 이건 아주 간단해요. 그래서 여기 무슨 문제가 있는 건 아닌 것 같아요.
get 'social_kredit/credit_tweet'
post '/credit_tweet' => 'social_kredit#credit_tweet'
이 오류는 어디에 있나요?나는 HTTP 요청에 대해 전혀 알지 못한다.
됐다!
추가...
skip_before_action :verify_authenticity_token
컨트롤러에 접속합니다.
로그를 체크 아웃 했을 때 CSRF 토큰을 검증할 수 없었던 것이 확인되었습니다.
ihaztehhcodez (2016년에 마지막으로 활동했으므로 답변을 올리도록 그를 자극하는 것은 도움이 되지 않을 것입니다)는 다음과 같이 언급합니다.skip_before_action :verify_authenticity_token위조 방지 기능을 상실하기 때문에 기술이 안전하지 않습니다.
베스트/시큐어/'베스트 프랙티스'라고 기재되어 있습니다.경고: CSRF 토큰의 신뢰성을 확인할 수 없습니다.
예.
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
또는
$.ajax({ url: 'YOUR URL HERE',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
data: 'someData=' + someData,
success: function(response) {
$('#someDiv').html(response);
}
});
또는
이를 Ajax 요청 내에 넣기
headers: {
'X-Transaction': 'POST Example',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
내가 직면했던 것과 같은 문제.추가 후 분류됩니다.
skip_before_action : skip_skip_skipsity_
컨트롤러 상단에서 JS가 데이터를 호출 또는 전송하고 있습니다.
class UserController < ApplicationController
skip_before_action :verify_authenticity_token
def create
end
end
코드 스니펫에 나타나 있듯이
Rails 6 API 전용 어플리케이션에서 작업할 때 이 문제가 있었습니다.
나는 여기 답을 따랐다 - 레일즈: Rails API 모드에서 protect_from_forgy를 구현하여 Rails API 모드에서 protect_from_forgy를 구현하는 방법, 그러나 저는 여전히 Rails API 모드에서 protect_from_forgy를 구현하고 있었습니다.Can't verify CSRF token authenticity에러에 이어422 Unprocessable EntityPostman에서 우편 요청을 보낼 때 오류 발생:
Started POST "/api/v1/programs" for ::1 at 2021-02-23 18:42:49 +0100
Processing by Api::V1::ProgramsController#create as JSON
Parameters: {"program"=>{"name"=>"Undergraduate", "code"=>"UD", "affiliate_status"=>false, "motto"=>"Our motto is ...", "description"=>"This is a new program", "school_id"=>1}}
Can't verify CSRF token authenticity.
TRANSACTION (0.3ms) BEGIN
↳ app/controllers/api/v1/programs_controller.rb:27:in `create'
Baserecord::School Load (0.3ms) SELECT "schools".* FROM "schools" WHERE "schools"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/api/v1/programs_controller.rb:27:in `create'
TRANSACTION (0.4ms) ROLLBACK
↳ app/controllers/api/v1/programs_controller.rb:27:in `create'
Completed 422 Unprocessable Entity in 30ms (Views: 0.8ms | ActiveRecord: 6.9ms | Allocations: 13172)
해결 방법은 다음과 같습니다.
이 문제는 내 모델의 인증 오류로 인해 발생했습니다.호출한 컨트롤러 모델에 추가한 검증이 실패했습니다.오류를 찾기 위해 요청을 한 후 우체국에서 반환한 답변의 본문을 확인해야 했습니다.
{
"affiliate_status": [
"can't be blank"
]
}
랜덤 부울 속성을 설정할 때 "Rails: Validation for Active Record" (Active Record 검증 실패) 에러를 수정하면 모든 것이 정상적으로 동작합니다.
그게 다예요.
이게 도움이 됐으면 좋겠다
POST 요청에서 모델을 업데이트하면 422가 발생할 수 있습니다.
★★@user.update!(email: nil)users#update 메일의 유효성이 .validates :email, presence: true
Rails를 사용합니다.<%= csrf_meta_tags %>다음을 생성합니다.
<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="ihwlaOLL232ipKmWYaqbSZacpJegQqooJ+Cj9fLF2e02NTQw7P/MfQyRuzruCax2xYWtEHWsb/uqiiZP6NWH+Q==" />
CRSF 토큰을 메타데이터에서 꺼내 비동기 요구에 전달할 수 있습니다. js fetch이라고 할 수 있습니다.x-csrf-token머리글
표준 레일 양식을 향상시키는 React 구성요소에 대한 잘린 onSave 핸들러입니다.
onSaveHandler = (event) => {
const data = "Foo Bar";
const metaCsrf = document.querySelector("meta[name='csrf-token']");
const csrfToken = metaCsrf.getAttribute('content');
fetch(`/posts/${this.props.post_id}`, {
method: "PUT",
body: JSON.stringify({
content: data
}),
headers: {
'x-csrf-token': csrfToken,
'content-type': 'application/json',
'accept': 'application/json'
},
}).then(res => {
console.log("Request complete! response:", res);
});
}
위조 방지는 좋은 생각입니다.이렇게 하면 안전성이 유지되고 레일 구성을 망치지 않습니다.
「」를 사용합니다.gem 'rails', '~> 5.0.5'&"react": "^16.8.6",
언급URL : https://stackoverflow.com/questions/27098239/rails-post-422-unprocessable-entity-in-rails-due-to-the-routes-or-the-contro
'codememo' 카테고리의 다른 글
| Wordpress WooCommerce StoreFront 헤더 스타일 제거 (0) | 2023.02.12 |
|---|---|
| 메이븐 의존성 spring-web vs spring-webmvc (0) | 2023.02.12 |
| jsonb 필드의 PostgreSQL 이름 변경 특성 (0) | 2023.02.12 |
| Bad Image Format Exception 입니다.이 문제는 32비트 Oracle 클라이언트 컴포넌트가 설치된 상태에서 64비트 모드로 실행 중일 때 발생합니다. (0) | 2023.02.12 |
| 장애/오류 발생 시 JSON 서비스가 반환해야 할 항목 (0) | 2023.02.12 |