반응형
Vue SSR serverPrefetch server 리디렉션$ssrContext.res.redirect
서버 콘솔에서 오류 없이 VUE SSR의 구성 요소에서 리디렉션을 수행할 수 있는가?[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
?
코드는 다음과 같다.
serverPrefetch() {
// need the data from this.fetchPage service to decide on the redirect
return this.fetchPage().then(function (response) {
// do some checks here
// THIS IS THE NODE EXPRESS REDIRECT
this.$ssrContext.res.redirect('/');
this.$ssrContext.res.end(); // with or without, same error
}.bind(this));
},
beforeMount() {
this.fetchPage();
}
참고: 사용하려는 경우this.$router.replace('/')
(또는 다른 방법) 오류가 표시됨:[Vue warn]: Error in callback for watcher $route: ReferenceError: document is not defined
.
내 프로젝트에서 나는 클라이언트 쪽에서 리디렉션을 했지만, 서버에서도 이 작업이 가능한지 궁금했다.
TL;DR:
{url: '/redirect-route'}을(를) 사용하여 서버Prefetch 거부
다음과 같이 해결책을 찾았다.vue-ssr 프로젝트를 https://github.com/vuejs/vue-hackernews-2.0 repo로 구현하는 경우 server/index.js에는 리디렉션이 있는 handleError 기능이 있다.
if (err.url) {
res.redirect(err.url);
}
구성 요소에서 해야 할 일은
serverPrefetch() {
return this.fetchPage().then(res => {
if(res === 'MY_REDIRECT_CONDITION') {
// !!! THE ACTUAL REDIRECT TRIGGER !!!
return Promise.reject({url: '/'});
}
});
},
반응형
'programing' 카테고리의 다른 글
Create-React-app 프로젝트를 테스트할 때 "ReferenceError: 문서가 정의되지 않음" (0) | 2022.03.10 |
---|---|
반응: 라디오 버튼 컬렉션에 선택한 항목이 있는지 확인하는 방법 (0) | 2022.03.10 |
Vue 라우터를 사용하여 리디렉션할 때 매개 변수를 전달하는 방법 (0) | 2022.03.10 |
Typecript Vuex 객체가 알 수 없는 유형인 Vue Vuex (0) | 2022.03.10 |
UnicodeEncodeError: 'ascII' 코덱이 위치 20에서 문자 u'\xa0'을 인코딩할 수 없음: 서수가 범위(128)에 없음 (0) | 2022.03.10 |