나는 반응 + 타이프 스크립트에 프론트 엔드가 있고 go iris에 백엔드가있는 블로그 응용 프로그램을 작성했습니다. 블로그 콘텐츠 가져 오기 요청을 받고 있습니다. 백엔드는 localhost : 5000 및 노드는 localhost : 3000에서 실행되지만 오류와 함께 실패합니다.
교차 출처 요청 차단됨 : 동일한 출처 정책이 http : // localhost : 5000 / getposts 에서 원격 리소스 읽기를 허용하지 않습니다 . (이유 : CORS 헤더 'Access-Control-Allow-Origin'누락).
백엔드에 CORS를 이미 구성했습니다.
Cors := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"},
AllowCredentials: true,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"},
AllowedHeaders: []string{"Cache-Control", "X-File-Name", "X-Requested-With", "X-File-Name", "Content-Type", "Authorization", "Set-Cookie", "Cookie"},
Debug: true,
})
authConfig := basicauth.Config{
Users: map[string]string{USER_NAME: PASSWORD},
Realm: "Authorization Required", // defaults to "Authorization Required"
Expires: time.Duration(30) * time.Minute,
}
authentication := basicauth.New(authConfig)
app := iris.New()
app.Use(Cors)
app.Get("/getposts", authentication, GetPostsHandler)
이것이 내가 요청을 보내는 방법입니다.
fetch("http://localhost:5000/getposts", {
method: "get",
credentials: "include",
mode: "cors",
headers: [
["Content-Type", "application/json"],
["Authorization", "Basic " + btoa("Sreyas:password")]
]
})
.then(response => {
if (response.ok) {
response.json().then(rawdata => {
this.setState({ blogdata: rawdata });
});
} else {
console.log("No posts");
this.setState({ blogdata: null });
}
})
.catch(error => {
console.log("Server Error");
this.setState({ blogdata: null });
});
이 문제를 해결하기 위해 몇 시간 동안 검색하고 시도했지만 운이 없었습니다.
nginx를 사용하라는 그의 제안에 대해 Slotheroo에게 감사 드리며 이것이 제가이 문제를 해결할 수있는 유일한 방법이었습니다. 저는 nginx를 사용하여 요청을 프록시하고 프런트 엔드와 백 엔드를 8000 포트로 라우팅했습니다. 내 nginx 서버 구성 샘플과 코드 변경 사항을 여기에 남겨 두어 향후 누구에게나 도움이 될 것입니다. :)
( "localhost"와 같은 루프백 IP를 사용하면 요청을로드하고 보낼 때 성능에 영향을 미칠 수 있으므로 이러한 성능 문제를 극복하기 위해 시스템의 정확한 IP를 사용합니다.)
nginx.conf
server {
listen 8000;
server_name localhost;
location / {
proxy_pass http://localhost:3000;
}
location /getposts {
proxy_pass http://localhost:5000/getposts;
}
}
백엔드의 허용 된 Orgins에 localhost : 8000을 추가했습니다.
AllowedOrigins: []string{"http://localhost:8000"},
요청은 이제 8000 포트로 전송됩니다.
fetch('http://localhost:8000/getposts',{
method: 'get',
credentials: "include",
mode: "cors",
headers: [
["Content-Type", "application/json"],
["Authorization","Basic "+btoa('Sreyas:password')],
]
}).then((response) => {
if(response.ok){
response.json().then(rawdata =>{
this.setState({blogdata:rawdata})
})
}else{
console.log("No posts")
this.setState({blogdata:null})
}
}).catch(error => {
console.log("Server Error")
this.setState({blogdata:null})
})
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다