我从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
<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware
{
/**
* 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', "*")
->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.
使用curl方式发生错误,初步猜测是因为请求端和响应端都是laravel,APP_KEY问题?不懂。
将APP_KEY设置成相同,去掉VerifyCsrfToken中间件,顺利返回结果。
我使用的laravel5.1版的最新版,也可以在app/Http/Middleware/VerifyCsrfToken.php的$except数组中加上要跳过Csrf验证的路由。
此时,angular $http 使用jsonp、get都没有问题。jquery的ajax方法也都可以。
angular post需要加上头部信息'Content-Type': 'application/x-www-form-urlencoded',顺利得到结果。
以下使用方式被转成OPTIONS,发生问题中的origin错误。