我从a.com发送一个post请求到b.com,显示状态200,但是 failed to load response data.
a.com 请求如下:
$http.post('http://www.b.com/test/index', {
name: 'testname',
email: 'testemail@qq.com'
}).then(function (r) {
console.log(r);
});
b.com返回响应:
// test/index路由指向TestController@index方法,如下:
public function index(Request $request)
{
foreach (array_keys($this->fields) as $field) {
//if(!$request->has($field)) return false;
$this->orderInfo[$field] = $request->get($field);
}
return response()->json(['status' => 1, 'msg' => 'success'])
->header('Access-Control-Allow-Origin', 'http://www.a.com')
->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept')
->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
}
以上代码在a.com结果如下图:


还有测试如下:如果header('Access-Control-Allow-Origin', 'http://www.a.com')改成通配符*,返回500,

在请求中加上withCredentials: true,,同500。
是不是我哪里设置有错?怎么样才能取得response的数据呢?
改成中间件版,如下:
// a.com 发起请求
$http.post('http://www.b.com/test/index', {
name: 'testname',
email: 'testemail@qq.com'
}).then(function (r) {
console.log(r);
});
b.com里的代码
//路由
Route::post('test/index', ['middleware' => 'enblecross', 'uses' => 'TestController@index']);
//中间件 EnableCrossRequestMiddleware.php
header('Access-Control-Allow-Origin', "*")
->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept')
->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
//$response->header('Access-Control-Allow-Credentials', 'true');
return $response;
}
}
// 注册
protected $routeMiddleware = [
//....
'enblecross' => \App\Http\Middleware\EnableCrossRequestMiddleware::class,
];
//TestController@index
public function index(Request $request)
{
return ['status' => 1, 'msg' => 'success'];
}
结果还是一样,偶尔500,偶尔200,报错Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
是这样的,首先是发了一个OPTIONS的预请求,来询问服务器是否接受这次的跨域请求。
接下来才会发正式请求,来接收数据。你找一下看看应该有个POST的响应。你看到的这个是OPTIONS的响应,自然是没有实体数据的。