为什么会发生这种情况有很多因素。该错误可能会发生,因为您没有访问标头,并且浏览器得到了这个并阻止了您的请求。
当您的服务器遇到内部错误(例如 500,403,401 等)时也会发生这种情况。您可能在 laravel 应用程序中的请求生命周期中添加了标头(例如在中间件中过滤所有 api 请求),但有时会出现错误 500 甚至是 echo 或 dd () 会中断整个请求生命周期并返回浏览器无法通过 ajax 调用解释的错误,因此它会丢失您隐式添加的标头,因此浏览器会返回到预检请求错误。
我建议的唯一解决方案是在代码中正确处理错误并在响应中返回错误并以 json 格式返回。
public function someController extends Controller{
public function Foo(Request $request){
$input_bag = [
'some input' => first_$input,
'another important input' => $second_input,
];
$i = 0;
foreach ($input_bag as $key => $value) {
$value = trim($value);
if (empty($value)) {
$error_bag[$i] = "$key empty";
$i++;
} else {
//
}
}
//filter of false or null values
if (array_filter($error_bag)) {
return response()->json($error_bag, 400);
}
}
这会在运行代码时返回错误的 json 响应。良好地使用 try catch 并返回适当的响应可以使您的调试生活变得轻松。