我一直在遵循本指南:https://www.freecodecamp.org/news/how-to-build-a-keyword-density-tool-with-laravel/ 并在最后发现我的应用程序不会返回任何数组。事实上,当我点击提交按钮时,我注意到我收到了一个 419 控制台错误。在检查了与 CSRF 令牌相关的大多数问题后,但从检查中我发现这是正确的。
任何人都可以发现或引导我朝着正确的方向前进,以便我的应用返回一些东西。它不是很先进,实际上它是一个非常简单的应用程序,但这是我第一次使用 Laravel,因此不胜感激。
我的 index.blade.php(包含表单和ajax请求)
@extends('layouts.master')
@section('content')
<form id="keywordDensityInputForm">
<div class="form-group">
<label for="keywordDensityInput">HTML or Text</label>
<textarea class="form-control" id="keywordDensityInput" rows="12"></textarea>
</div>
<button type="submit" class="btn btn-primary mb-2">Get Keyword Densities</button>
</form>
@endsection
@section ('scripts')
<script>
$('#keywordDensityInputForm').on('submit', function (e) { // Listen for submit button click and form submission.
e.preventDefault(); // Prevent the form from submitting
let kdInput = $('#keywordDensityInput').val(); // Get the input
if (kdInput !== "") { // If input is not empty.
// Set CSRF token up with ajax.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({ // Pass data to backend
type: "POST",
url: "tool/calculate-and-get-density",
data: {'keywordInput': kdInput},
success: function (response) {
// On Success, build a data table with keyword and densities
if (response.length > 0) {
let html = "<table class='table'><tbody><thead>";
html += "<th>Keyword</th>";
html += "<th>Count</th>";
html += "<th>Density</th>";
html += "</thead><tbody>";
for (let i = 0; i < response.length; i++) {
html += "<tr><td>"+response[i].keyword+"</td>";
html += "<td>"+response[i].count+"</td>";
html += "<td>"+response[i].density+"%</td></tr>";
}
html += "</tbody></table>";
$('#keywordDensityInputForm').after(html); // Append the html table after the form.
}
},
});
}
})
</script>
@endsection
我的master.blade.php(头部CSRF令牌)
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Keyword Density Tool</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
body {padding-top: 5em;}
</style>
</head>
<body>
...
<main role="main" class="container mt-3">
@yield('content')
</main><!-- /.container -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
@yield('scripts')
</body>
</html>
我的控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Html2Text\Html2Text;
class ToolController extends Controller
{
public function index()
{
return view('tool.index');
}
public function CalculateAndGetDensity(Request $request) {
if ($request->isMethod('GET')) {
if (isset($request->keywordInput)) { // Test the parameter is set.
$html = new Html2Text($request->keywordInput); // Setup the html2text obj.
$text = strtolower($html->getText()); // Execute the getText() function and convert all text to lower case to prevent work duplication
$totalWordCount = str_word_count($text); // Get the total count of words in the text string
$wordsAndOccurrence = array_count_values(str_word_count($text, 1)); // Get each word and the occurrence count as key value array
arsort($wordsAndOccurrence); // Sort into descending order of the array value (occurrence)
$keywordDensityArray = [];
// Build the array
foreach ($wordsAndOccurrence as $key => $value) {
$keywordDensityArray[] = ["keyword" => $key, // keyword
"count" => $value, // word occurrences
"density" => round(($value / $totalWordCount) * 100,2)]; // Round density to two decimal places.
}
return $keywordDensityArray;
}
}
}
}
?>
和我的路线
Route::get('/tool', 'App\Http\Controllers\ToolController@index')->name('KDTool');
Route::post('/tool/calculate-and-get-density', 'App\Http\Controllers\ToolController@CalculateAndGetDensity');
我得到的错误是这个
我已经检查了有关 stackoverflow 的所有其他答案建议,但我所做的一切似乎都没有让我更进一步。提前感谢您的任何帮助