【发布时间】:2016-04-01 07:36:15
【问题描述】:
我使用 Lumen 构建了一个 API,并希望使用 JavaScript 和 XMLHttpRequest 对象来访问它。但每次我的 PUT、GET、POST 和 DELETE 请求都转换为 OPTIONS - Request。我阅读了很多有关 CORS 信息的网站。我构建的中间件内容如下:
class CORSMiddleware
{
public function handle($request, \Closure $next)
{
$response = null;
/* Preflight handle */
if ($request->isMethod('OPTIONS')) {
$response = new Response();
} else {
$response = $next($request);
}
$response->header('Access-Control-Allow-Methods', 'OPTIONS, HEAD, GET, POST, PUT, DELETE');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');
return $response;
}
}
我的客户代码:
var url = "http://localhost:8000/api/user";
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open('PUT', url, false);
xmlHttpRequest.send('{"username": "ABC", "password": "ABC","email": "mail@cool.xyz" }');
if (xmlHttpRequest.status == 200) {
console.log(xmlHttpRequest.responseText);
}
我的GET请求信息:
Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Origin: null
Connection: keep-alive
Cache-Control: max-age=0
我的 GET 请求响应信息:
Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sun, 27 Dec 2015 10:36:51 GMT
Host: localhost:8000
x-powered-by: PHP/7.0.0
我的 PUT 请求的请求信息:
Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: PUT
Origin: null
Connection: keep-alive
Cache-Control: max-age=0
我的一个 PUT 请求的响应信息:
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sun, 27 Dec 2015 10:36:51 GMT
Host: localhost:8000
x-powered-by: PHP/7.0.0
在预检中没有“Access-Control-Allow-*”-Headers。我不知道为什么;我用我的 lumen-cors-middleware 启用了它。
【问题讨论】:
-
听起来您的请求正在触发浏览器首先发送a CORS preflight。没有办法解决这个问题。它是浏览器中关于跨域请求的必需行为。因此,您可能需要阅读 CORS 文档并相应地更新您的代码。
-
在
PUTAJAX 请求和许多其他情况下,浏览器会生成您尝试处理的预检请求。您的具体问题是什么? -
没有 POST、PUT 或 DELETE 请求有效 - 没有响应是我的问题 :-) GET 请求有效
-
我已经使用给定的 php 代码进行了预检。但它为什么不起作用?
标签: javascript cors lumen