Php 使用Curl调用Slim CORS Web服务
我在使用Curl让Slim CORS web服务工作时遇到问题 当从基于浏览器的Ajax服务调用时,它可以正常工作,但当从服务器上的脚本调用时,我无法使它正常工作。CORS已设置为允许从“*”访问Php 使用Curl调用Slim CORS Web服务,php,curl,cors,slim,Php,Curl,Cors,Slim,我在使用Curl让Slim CORS web服务工作时遇到问题 当从基于浏览器的Ajax服务调用时,它可以正常工作,但当从服务器上的脚本调用时,我无法使它正常工作。CORS已设置为允许从“*”访问 $url = "https://server.local/api/v1.0/issueJWTToken"; $ch1 = curl_init(); $headers = [ "Origin: https://server.local", "Content-Type: text/pl
$url = "https://server.local/api/v1.0/issueJWTToken";
$ch1 = curl_init();
$headers = [
"Origin: https://server.local",
"Content-Type: text/plain",
"Access-Control-Request-Headers: Content-Type, Origin"
];
curl_setopt_array($ch1, array(
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => 'OPTIONS',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_NOBODY => true,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => false
));
$data = curl_exec($ch1);
curl_close($ch1);
这将返回以下内容:
HTTP/1.1 200 OK
Date: Mon, 04 Jun 2018 12:33:51 GMT
Server: Apache/2.4.10 (Debian)
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept,
Origin, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Content-Length: 0
Content-Type: text/html;
charset=UTF-8
随后,我将进行如下的后期交易:
$post_fields = "id=1" ;
$headers = [
"Origin: https://server.local",
"Content-Type: text/plain"
];
$ch = curl_init();
curl_setopt_array($ch,[
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS=> $post_fields,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => false
]);
$data = curl_exec($ch);
但我得到了以下信息
HTTP/1.1 405 Method Not Allowed
Date: Mon, 04 Jun 2018 12:38:02 GMT Server: Apache/2.4.10 (Debian)
Allow: OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Content-Length: 559
Content-Type: text/html;charset=UTF-8
<html>
<head>
<title>Method not allowed</title>
</head>
<body>
<h1>Method not allowed</h1>
<p>Method not allowed. Must be one of: <strong>OPTIONS</strong></p>
</body>
</html>
原来是我做了个白痴。我把API的URL路径弄错了。哦。感谢你们中做出回应的人。尼尔我不知道答案,但我可以告诉你的是,选项是一个飞行前的请求,基本上会问服务器“我的请求有效吗?”你可以阅读。通常由浏览器发布。然而,我发现这可能会对你有所帮助。“选项回复中是否有我应该在帖子中传回的内容?”-通常不会。您正在谈论的API可能有奇怪的需求。该API是我的,使用Slim实现。我已经按照上面的详细说明设置了CORS详细信息。当从浏览器将Javascript作为Ajax服务调用时,它适用于所有事务类型。当使用Curl从同一服务器上的PHP脚本调用它时,我就是无法让它工作
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});