版权声明:经验之谈,不知能否换包辣条,另,转载请注明出处。 https://blog.csdn.net/zhezhebie/article/details/90693220
前后端交互的时候,遇到跨域问题,我前端直接使用的是postman里面code代码,然后报错了,原因是我后端允许的header头里面不包含cache-control和postman-token,所以会爆出如下错误:
element.style {
}
user agent stylesheet
body {
display: block;
margin: 8px;
}
index.html:1 Access to XMLHttpRequest at 'http://xxx:88/api/xx/index' from origin 'http://test.com' has been blocked by CORS policy: Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.
前端测试代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>123124</h1>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
var form = new FormData();
form.append("email", "[email protected]");
form.append("password", "password");
var settings = {
"async": true,
"crossDomain": true,
"url": "http://xxx/api/product/index",
"method": "GET",
"headers": {#就是这里导致上面的错误
"Cache-Control": "no-cache",
"Postman-Token": "6a627352-c28b-4853-b59a-1f6f753e66e6"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});
</script>
</html>
解决办法有两个:
1.前端请求里面去掉headers里面的cache-control和postman-token
1.后端中间件里面headers里面允许cache-control和postman-token
<?php
namespace App\Http\Middleware;
use Closure;
class CrossHttp {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, cache-control,postman-token,Cookie, Accept');#注意这里
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
// $response->header('Access-Control-Allow-Credentials', 'true');
return $response;
}
}
再次请求即可。