나는 SLIM 마이크로 프레임 워크로 API를 만들었습니다. 다음 코드를 사용하여 CORS 헤더를 추가하는 미들웨어를 설치했습니다.CORS 게시물 요청 실패
class Cors{
public function __invoke(Request $request, Response $response, $next){
$response = $next($request, $response);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
프런트 엔드의 경우 VueJS를 사용했습니다. 설치 VueResource 및 다음 코드 사용하여 함수를 만들었습니다.
register (context, email, password) {
Vue.http({
url: 'api/auth/register',
method: 'POST',
data: {
email: email,
password: password
}
}).then(response => {
context.success = true
}, response => {
context.response = response.data
context.error = true
})
}
크롬에서 다음 오류가 콘솔에 기록됩니다.
XMLHttpRequest cannot load http://mysite:9800/api/auth/register. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysite' is therefore not allowed access.
이상하게도 GET 요청은 완벽하게 작동합니다.
감사합니다 !!! 좋은 대답입니다, 친구. 이제 완벽하게 작동합니다. 나는 너없이 그것을 할 수 없었다. –
@geggleto 제 지식에 따라 CORS의 경우 브라우저 클라이언트가 OPTIONS의 비행 요청을하기위한 위임장을 가지고 있으며 위에서 언급 한 응답 헤더의 유효성을 확인했습니다. OPTIONS를 비활성화하고 해당 헤더를 설정하지 않으면 오류가 발생한다는 의미입니까? 그런 요청을 할 때마다 response.Send (200);를 반환해야합니다. – xploreraj