【发布时间】:2018-02-13 23:13:19
【问题描述】:
我们在一个已经使用 webpack 的项目上使用vue-bulma-admin 脚手架,我们似乎无法对我们的 API 执行任何 POST/PUT 请求(它已经将 access-cross-allow-origin 标头设置为 * ),只有 GET 请求有效。从使用我们 API 的不同前端,我们没有这个问题,只有这个特定的前端,它给出了这个常见的错误:
“请求中没有“Access-Control-Allow-Origin”标头 资源。”
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
我们已经尝试在axios/vue-resource 上设置自定义标题,但没有成功。正如我所说,通过 Postman/不同前端使用相同的路由或使用 CORS chrome 扩展,一切正常。
有什么想法可以解决这个问题吗?
我在 Laravel API 中的中间件 Cors。
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
【问题讨论】:
-
你也设置了Access-Control-Allow-Methods吗?
-
我用它编辑了我的问题。
-
听起来您的 POST 至少添加了一个标头(可能是 Content-Type 标头?),这会触发您的浏览器自动执行 CORS 预检 OPTIONS 请求 developer.mozilla.org/en-US/docs/Web/HTTP/… 和看来该服务器的后端代码未配置为发送 OPTIONS 请求的 Access-Control-Allow-Origin 标头。它必须配置为使用 200 OK 响应 OPTIONS 请求,并且 Access-Control-Allow-Headers 和 Access-Control-Allow-Methods 标头具有正确的值。
-
有关处理 CORS 预检选项的示例代码,请参阅 stackoverflow.com/questions/8719276/cors-with-php-headers/…