角度POST请求不起作用,但GET工作正常

时间:2015-12-04 19:17:32

标签: angularjs laravel http-headers cors content-type

我知道有人问这个问题,但是我尝试了很多事情,但却无法做到这一点。

我正从我的角色应用程序向laravel后端api发出GET和POST请求。我能够从get请求获取json,但我的POST请求对于json数据类型失败。它适用于

x-www-form-urlencoded

但我无法以json格式提取数据。

$http.get('http://api.app.mywebsite.com/users').success(function(data){
    $scope.user = data;
});

$scope.addUser = function(user){
    console.log($scope.user);
    $http({
        method: 'POST',
        url: 'http://api.app.mywebsite.com/users',
        dataType: 'json',
        data: $scope.user,
        headers: {'Content-Type': 'application/json; charset=utf-8' }
    }).then(function(result){
        console.log(result);
    }, function(error){
        console.log(error);
    })
}

$scope.user is posted on form submit.

我得到的错误: -

XMLHttpRequest cannot load http://api.app.mywebsite.com/users. 
Response     to preflight request doesn't pass access control check: 
No 'Access-Control-    Allow-Origin' header is present on the 
requested   resource. Origin 'http://app.mybackend.com' is therefore not     allowed access.

laravel中的我的CORS.php中间件: -

public function handle($request, Closure $next)
{
    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin, X-Requested-With, Accept'
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return \Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
    return $next($request);
}

routes.php文件

Route::group(['middleware' => 'cors'], function()
{
    Route::resource('users', 'UserController');
});

1 个答案:

答案 0 :(得分:0)

相关问题