搜尋

首頁  >  問答  >  主體

vue.js - Laravel 使用vue-resource發送ajax請求怎麼加入CsrfToken

Laravel 使用vue-resource發送ajax請求怎麼加入CsrfToken,

下面是用formData傳送ajax請求demo:

{
  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
  });
}

上面程式碼會遇到CsrfToken問題,該怎麼加入?

阿神阿神2754 天前641

全部回覆(2)我來回復

  • phpcn_u1582

    phpcn_u15822017-05-16 16:53:11

    雷雷

    回覆
    0
  • 世界只因有你

    世界只因有你2017-05-16 16:53:11

    http://docs.spring.io/spring-...
    最下面

    <!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>

    回覆
    0
  • 取消回覆