Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight respo

前后端交互时遇到跨域问题,前端使用postman代码报错,原因是后端允许的header头不包含cache - control和postman - token。解决办法有两个,一是前端请求去掉headers里的这两项,二是后端中间件允许这两项,再次请求即可。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前后端交互的时候,遇到跨域问题,我前端直接使用的是postman里面code代码,然后报错了,原因是我后端允许的header头里面不包含cache-controlpostman-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", "zhezhebie@163.com");
	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;
    }

}

再次请求即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值