将数据从javascript发送到Laravel Controller

时间:2019-03-04 09:58:15

标签: javascript ajax laravel

从javascript向控制器发送数据时出现问题。 有我的 Ajax

var point = JSON.stringify(points);

function onBtnClick() {
    $.ajaxSetup({
      header:{
        'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
      }
    });

    $.post('http://localhost/updateC', {
        data: point,
        dataType: 'json', 
        contentType:'application/json', 
    })
    .done(function() {
        alert('success');
    })
    .fail(function() {
        alert("error");
    });

}

路线:

Route::get('/home', 'HomeController@index')->name('home');
Route::resource('/races','RacesController');
Route::post('updateC', 'RacesController@Points');

还有我的 RacesController:

public function Points(Request $request) {
    $test = $request->input('data');
    return "$test";
}

错误是说已被CORS政策阻止。

4 个答案:

答案 0 :(得分:0)

转到中间件文件夹,verifycsrftoken文件

app/Http/Middleware/VerifyCsrfToken.php

并将此网址添加到除外数组

protected $except = [
   ....
   http://localhost/updateC
];

处理ajax发布请求的异常,然后可以使用

Barryvdh Laravel Cors软件包以消除cors问题,

如果您使用的是laravel 5.6,则不需要任何CORs软件包,

只需创建CORs中间件

namespace App\Http\Middleware;
use Closure;
class Cors {

    public function handle($request, Closure $next) {
        $allowedOrigins = ['http://oursite.com', '*.myost.net','*','www.aminu.*'];
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        if (in_array($origin, $allowedOrigins)) {
            return $next($request)
                ->header('Access-Control-Allow-Origin', $origin)
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With, cache-control,postman-token, token')
                ->header('Access-Control-Allow-Credentials',' true');
        }
        return $next($request);
    }
}

并将中间件添加到kernel.php文件

protected $middleware = [
    ......
    \App\Http\Middleware\Cors::class, //added here
];

答案 1 :(得分:0)

您必须在ajax帖子的data属性中添加 csrf令牌,如下所示:

data: {
    "_token": "{{ csrf_token() }}",
    "point": point
}

答案 2 :(得分:0)

app/Http/Middleware/VerifyCsrfToken.php

并将此路由添加到除外数组

protected $except = [
   'updateC'
];

答案 3 :(得分:0)

Ajax代码

var abc = 'hello world';

$.ajax({
    type: "GET",
    url: 'http://your url',
    data : { abc : abc }
    success: function (data) {

        // write your code
    },
    error: function (data) {
        // write your code
    }
});