I'm new to web dev. I'm developing a laravel app with a google chrome extension to send a post request to laravel app using jquery ajax.
When I comment this line \App\Http\Middleware\VerifyCsrfToken::class,
in App\Http\Kernel.php
My form get posted and I hit Status Code: 200.
But if I uncomment that line I get Status Code: 419.
Here is my popup.html code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="styles/font-awesome.min.css">
<link href="styles/main.css" rel="stylesheet">
<script src="scripts/jquery-3.2.1.min.js"></script>
<script src="scripts/popup.js"></script>
</head>
<body>
<div class=" form-group content">
<p>
<h1 class="title"></h1>
</p>
<div>
<form id="form" method="POST" action="https://app.test/">
<input type="url" name="url" id="input" class=" form-control form-group input" autocomplete="off">
<div class="formbtn">
<button id="button" class="btn" type="submit">Publish </button>
</div>
</form>
</div>
</div>
</body>
</html>
Here is my popup.js code:
taburl = "";
chrome.tabs.query(
{
active: true,
lastFocusedWindow: true
},
function(tabs) {
// and use that tab to fill in out title and url
var tab = tabs[0];
var link = tab.url;
$("#input").val(link);
var str = tab.title;
var res = str.substring(0,20);
$('.title').html(res+ '...');
taburl = link;
}
);
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#button").on("click", ajaxCall);
});
$("#input").val(taburl);
function ajaxCall(element) {
$.ajax({
url : "https://app.test/",
data : {
"_token":"{{ csrf_token() }}",
"url" : taburl,
},
method : "POST",
success : function(data) {
alert("sent url = " + taburl);
}
});
}
Here is the screenshot of the network tab:
Use your api.php route instead. for security you can use laravel passport or something similar to create a token to authenticate your users or access token.
Hope this help!