Maison > Questions et réponses > le corps du texte
Comment ajouter CsrfToken lors de l'envoi d'une requête ajax dans Laravel à l'aide de vue-resource,
Ce qui suit est une démonstration de l'utilisation de formData pour envoyer une requête ajax :
{
var formData = new FormData();
// append string
formData.append('foo', 'bar');
// append Blob/File object
formData.append('pic', fileInput, 'mypic.jpg');
// POST /someUrl
this.$http.post('/someUrl', formData).then((response) => {
// success callback
}, (response) => {
// error callback
});
}
Le code ci-dessus rencontrera un problème CsrfToken. Comment dois-je l'ajouter ?
phpcn_u15822017-05-16 16:53:11
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name=csrf-token]').getAttribute('content')
</script>
世界只因有你2017-05-16 16:53:11
http://docs.spring.io/spring-...
Bas
<!DOCTYPE html>
<html>
<head>
<title>CSRF Protected JavaScript Page</title>
<meta name="description" content="This is the description for this page" />
<sec:csrfMetaTags />
<script type="text/javascript" language="javascript">
var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
// using XMLHttpRequest directly to send an x-www-form-urlencoded request
var ajax = new XMLHttpRequest();
ajax.open("POST", "http://www.example.org/do/something", true);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded data");
ajax.send(csrfParameter + "=" + csrfToken + "&name=John&...");
// using XMLHttpRequest directly to send a non-x-www-form-urlencoded request
var ajax = new XMLHttpRequest();
ajax.open("POST", "http://www.example.org/do/something", true);
ajax.setRequestHeader(csrfHeader, csrfToken);
ajax.send("...");
// using JQuery to send an x-www-form-urlencoded request
var data = {};
data[csrfParameter] = csrfToken;
data["name"] = "John";
...
$.ajax({
url: "http://www.example.org/do/something",
type: "POST",
data: data,
...
});
// using JQuery to send a non-x-www-form-urlencoded request
var headers = {};
headers[csrfHeader] = csrfToken;
$.ajax({
url: "http://www.example.org/do/something",
type: "POST",
headers: headers,
...
});
<script>
</head>
<body>
...
</body>
</html>