我构建了一个新的laravel 5.4项目。Laravel 5.4 Api Route 401
我试图在我的api路径中执行以下步骤,但不知何故,它们不起作用。
在我app.js文件,我有这样的Ajax调用:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
url: 'api/postStream',
type: 'post',
data: { imgData: imgData },
success:function(data) {
console.log('success');
}
});
我的API路线是这样的:
Route::group(['middleware' => 'auth:api'], function()
{
Route::post('postStream', ['as' => 'image', 'uses' => '[email protected]']);
});
而且我的控制器:
public function postStream(Request $request)
{
$imgData = $request->imgData;
...
}
但我在我的chrome dev控制台中得到这个错误:
POST http://localhost/app/public/api/postStream 401 (Unauthorized)
和网络工具这样的:
{error: "Unauthenticated."}
error
:
"Unauthenticated."
我想我有点不authentificated,但我不知道如何做到这一点这种方式。
这能帮助你吗? https://laracasts.com/discuss/channels/laravel/many-time-401-unauthorized-on-ajax-requests – Cr1xus
你确定你打的是正确的端点吗?我的猜测是http请求应该去http:// localhost/api/postStream。 – Unex
如果您使用'['middleware'=>'auth:api']',则需要传递访问令牌。遵循创建API,保护API和请求API密钥的步骤。首先你需要获得访问密钥,并通过ajax调用。我使用'Passport'为我的API提供身份验证。 https://laravel.com/docs/5.4/passport – webDev