搜索

首页  >  问答  >  正文

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问题,应该怎么添加?

阿神阿神2777 天前652

全部回复(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
  • 取消回复