【问题标题】:Laravel + Vue two same Projects but one CSRF ErrorLaravel + Vue 两个相同的项目,但一个 CSRF 错误
【发布时间】:2018-05-28 11:34:56
【问题描述】:

我有 2 个项目,其中 laravel 基本代码相同,但在一个项目中 vue.js 部分更高级。 现在我在 javascript 控制台中有一条奇怪的错误消息。

CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token

在我的下一步中,我复制了旧版本的功能性 vue 代码,但同样的错误。 我复制的代码在另一个项目中工作

引导代码相同,如下所示:

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap-sass');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

比我在 bootstrap.js 代码中做一些测试是这样的:

console.log(token);

结果为空。

我能做什么?

【问题讨论】:

    标签: javascript laravel vue.js vuejs2 axios


    【解决方案1】:

    尝试使用window.token 而不是token

    【讨论】:

      【解决方案2】:

      你必须先在html监听器的meta标签中设置它:

      <meta name="csrf-token" content="{{ csrf_token() }}" />
      

      【讨论】:

      • 是的。如果不设置,其他项目将无法运行
      猜你喜欢
      • 2020-11-14
      • 1970-01-01
      • 2019-02-18
      • 2016-01-15
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多