【问题标题】:Vue.js resource not working with Laravel 5.3 out-of-box configVue.js 资源不适用于 Laravel 5.3 开箱即用配置
【发布时间】:2017-04-26 04:54:10
【问题描述】:

使用全新安装的 Laravel 5.3,包含并配置开箱即用的 Vue.js:

this.$http.get(url) 返回错误:

TypeError: this$1.$http 未定义

将其替换为Vue.http.get(url)...发出请求但无法发送预检选项:

CORS 预检通道的 CORS 标头“Access-Control-Allow-Headers”中缺少令牌“x-csrf-token”

app.js:

require('./bootstrap');
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');

let app = new Vue({
        el: '#app',

        mounted: () => {
            navigator.geolocation.getCurrentPosition((position) => {
                app.getZip(position);
            });
        },

        methods: {
            getZip: (position) => {
                let lat = position.coords.latitude;
                let long = position.coords.longitude;
                let url = encodeURI(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&sensor=false`);
                Vue.http.get(url).then((response) => {
                    let zip = response.body.results[0].address_components[5].short_name;
                    console.log(zip);
                });
            },
        },
    });

bootstrap.js:

window._ = require('lodash');

window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');

window.Vue = require('vue');
require('vue-resource');

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);

    next();
});

相关app.blade.php:

<meta id="token" name="csrf-token" content="{{ csrf_token() }}">
<script>
        window.Laravel = <?php echo json_encode([
            'csrfToken' => csrf_token(),
        ]); ?>
</script>

<script src="/js/app.js"></script>

gulpfile.js:

const elixir = require('laravel-elixir');

require('laravel-elixir-vue-2');

elixir(mix => {
    mix.sass('app.scss')
       .webpack('app.js');
});

如果我包含&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.min.js"&gt;&lt;/script&gt;,它将成功地向两者发出请求:

Vue.http.get(url)
this.$http.get(url)

为什么这不适用于 node_module? require('vue-resource')

【问题讨论】:

    标签: laravel vue.js laravel-5.3 node-modules vue-resource


    【解决方案1】:

    因为你使用了require。如果你使用 require,你需要像 browserifywebpack 这样的库,它允许我们拥有 node.js 样式的模块,可以编译在浏览器中使用。

    【讨论】:

    • 不。 Laravel 5.3 附带 webpack,这就是我用来编译的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2017-02-10
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2017-02-12
    相关资源
    最近更新 更多