json 419(unknown status)on PUT request using laravel

t30tvxxf  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(98)

我试图使用put请求更新数据库中的一个值,但我遇到了CSRF错误,我不知道如何在flutter中修复它,所以我使用Route::withoutMiddleware(['csrf']);
我希望记录更新,但我仍然有错误:
PUT http://localhost/update/email protected(https://stackoverflow.com/cdn-cgi/l/email-protection) 419(未知状态)
我还尝试在VerifyCsrfToken.php文件中添加http://localhost/*,我如何修复它?
laravel:

public function updateStatus(Request $request, $email)
    {
        $validatedData = $request->validate([
            'is_active' => 'required|string',
        ]);
        $record = AddSeller::where('email', $email)->firstOrFail();
        $record->is_active = $validatedData['is_active'];

        $record->save();
        return response()->json(['message' => 'Record updated successfully'], 200);
    }

Flutter

Future<void> updateState(String email, String newValue) async {
  final apiUrl = 'http://localhost/update/$email'; 
  final headers = {'Content-Type': 'application/json'};
  final requestData = {'is_active': newValue}; 
  try {
    final response = await http.put(
      Uri.parse(apiUrl),
      headers: headers,
      body: jsonEncode(requestData),
    );
    if (response.statusCode == 200) {
      print('Record updated successfully');
    } else {
      print('Failed to update record: ${response.body}');
    }
  } catch (e) {
    print('Error: $e');
  }
}
okxuctiv

okxuctiv1#

在为API定义路由时,不要在web.php中定义它们,因为大多数情况下有状态路由都是在那里定义的。相反,在api.php中定义API Routes,这些路由是无状态的,因此您不需要在请求中发送CSRF令牌。
因此,您需要在api.php中定义路由。同样默认情况下,这些路由的前缀是api\,因此您的新路由将是,

http://localhost/api/update/$email

相关问题