标签: vue-resource

Vuejs在渲染数据之前同步请求

我有单页面应用程序需要身份验证.当用户通过身份验证然后访问某些页面或点击浏览器中的重新加载按钮时,它将请求提供其身份验证数据的API.然后我有这样的错误:

[Vue warn]: Error when evaluating expression "auth.name": TypeError: Cannot read property 'name' of null (found in component: <navbar>)

导致此错误的原因是,当对api的请求尚未完成时,vue呈现auth数据.

是否可以使vue等待请求api直到完成,在vue渲染auth数据之前?

更清楚的是这里发生了什么.这是代码:

// main.js
import Vue from 'vue'
import App from './App.vue' // root vue
import store from './vuex/store' // vuex
import router from './router' // my router map

sync(store, router)
router.start(App, '#app')
// end main.js



// App.vue
<template>
  <main>
    <div class="wrapper">
      <router-view></router-view>
    </div>
  </main>
</template>

<script>
  import authService from './services/auth' // import authservice

  ready () …
Run Code Online (Sandbox Code Playgroud)

javascript synchronous vue.js vue-resource

12
推荐指数
1
解决办法
2万
查看次数

基本的vue.js 2和vue-resource http得到变量赋值

我真的很难在vue.js 2中使用最基本的REST功能.

我想从某个端点获取数据并将返回的值分配给我的Vue实例的变量.这是我有多远.

var link = 'https://jsonplaceholder.typicode.com/users';
var users;

Vue.http.get(link).then(function(response){
    users = response.data;
}, function(error){
    console.log(error.statusText);
});

new Vue ({
    el: '#user-list',
    data: {
        list: users
    }
});
Run Code Online (Sandbox Code Playgroud)

在promise中,我可以访问响应数据,但我似乎无法将其分配给用户甚至是Vue实例的数据.

毋庸置疑,我对vue.js全新,并感谢任何帮助.

Stack:vue.js 2.03,vue-resource 1.0.3

干杯!

javascript vue.js vue-resource

11
推荐指数
1
解决办法
2万
查看次数

如何在vuex商店中使用vue-resource($ http)和vue-router($ route)?

在我从组件的脚本中获取电影细节之前.该功能首先检查商店的电影ID是否与路线的参数电影ID相同.如果相同则不从服务器API获取电影,否则从服务器API获取电影.

它工作正常.但现在我正试图从商店的变异中获取电影细节.但是我收到了错误

未捕获的TypeError:无法读取未定义的属性'$ route'

如何使用vue-router ($route)访问params和vue-resource ($http)以从vuex存储中的服务器API获取?

store.js:

export default new Vuex.Store({
    state: {
        movieDetail: {},
    },
    mutations: {
        checkMovieStore(state) {
            const routerMovieId = this.$route.params.movieId;
            const storeMovieId = state.movieDetail.movie_id;
            if (routerMovieId != storeMovieId) {
                let url = "http://dev.site.com/api/movies/movie-list/" + routerMovieId + "/";
                this.$http.get(url)
                    .then((response) => {
                        state.movieDetail = response.data;
                    })
                    .catch((response) => {
                        console.log(response)
                    });
            }
        },
    },
});
Run Code Online (Sandbox Code Playgroud)

组件脚本:

export default {
    computed: {
        movie() {
            return this.$store.state.movieDetail;
        }
    },
    created: function () {
        this.$store.commit('checkMovieStore');
    },
}
Run Code Online (Sandbox Code Playgroud)

javascript vue-resource vue-router vuex vuejs2

10
推荐指数
1
解决办法
5277
查看次数

显示临时标头和待处理请求

我有一个vue资源问题导致临时标题显示在chrome上,另一方面使用Jquery工作没有任何问题

问题只发生在chrome + vue-resource上

错误

复制链接

Chrome 57.0.2987 Windows 7

我没有安装adblock或origin,甚至在chrome上的访客模式下也会发生

一个简单的setInterval调用集

new Vue({

  el: '#main',

  data: {
    summary: null
  },
        methods: {
            updateSummary: function() {
      /*
                $.post( "summary.php", function( data ) {
                    if(typeof response.body.summary != 'undefined'){
                        this.summary = response.body.summary;
                    }
                });
        */
                this.$http.post('summary.php').then(function(response) {
                    if(typeof response.body.summary != 'undefined'){
                        this.summary = response.body.summary;
                    }
                });
            }
      },
        mounted: function () {
            this.updateSummary();

            setInterval(function () {
                this.updateSummary();
            }.bind(this), 2000);
        }
});
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/7vo2s8z3/1/

重现步骤

通常情况下,当我打开页面几个小时

什么是预期的?

提供内容的200代码响应

究竟发生了什么?

我收到了这些标题的请求

请求网址:http: …

javascript php google-chrome vue-resource

10
推荐指数
1
解决办法
2万
查看次数

在客户端设置Access-Control-Allow-Origin后,即使出现CORS错误

我有一个使用webpack-simple选项生成的Vue应用程序.我正在尝试发出GET请求,https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en但我收到错误:

XMLHttpRequest无法加载 https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en.对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.http://127.0.0.1:8080因此,不允许访问" 来源" .

我正在使用vue-resource并添加了:

Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'
Run Code Online (Sandbox Code Playgroud)

那没有效果.

我还在以下devServer选项中添加了这个webpack.config.js:

devServer: {
  historyApiFallback: true,
  noInfo: true,
  headers: {
    "Access-Control-Allow-Origin": "*"
  }
}
Run Code Online (Sandbox Code Playgroud)

这也不能解决问题; 错误消息保持不变.

如何解决这个问题?

cors webpack vue.js webpack-dev-server vue-resource

10
推荐指数
1
解决办法
2万
查看次数

Vuejs和Laravel Post请求CORS

我不懂.我几个小时以来一直在努力

我在Laravel中使用Vue.js并尝试向外部API发出POST请求.

但我总是在我的Vue POST请求上收到CORS错误

methods: {
            chargeCustomer(){
                this.$http.post('/api/chargeCustomer', this.payment).then(function (response) {
                    console.log(response.data)
                },function (response) {
                    console.log(response.data)
                });
            }
        }
Run Code Online (Sandbox Code Playgroud)

错误

MLHttpRequest无法加载 https://www.mollie.com/payscreen/select-method/JucpqJQses.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问" https://payment.dev ".

我为我的后端安装了Laravel CORS包,并将中间件添加到我的路线中,例如

Route::group(['middleware' => 'cors'], function(){
    Route::post('/api/chargeCustomer', 'Backend\PaymentController@chargeCustomer');
});
Run Code Online (Sandbox Code Playgroud)

但我仍然得到错误.我还尝试添加Vue Headers

Vue.http.headers.common['Access-Control-Allow-Origin'] = '*';
Vue.http.headers.common['Access-Control-Request-Method'] = '*';
Run Code Online (Sandbox Code Playgroud)

具有相同的结果/错误.

有人能告诉我我做错了什么吗?

cors laravel vue.js vue-resource

9
推荐指数
1
解决办法
4646
查看次数

如何在Vue实例的beforeCreate钩子中进行异步调用?

我正在使用身份验证构建Vuejs应用程序.

当页面加载并初始化appVuejs实例时,我使用beforeCreatehook来设置用户对象.我从中加载JWT localStorage并将其发送到后端进行验证.

问题是这是一个异步调用,并且app在调用返回验证结果之前,使用空的用户数据初始化此对象的组件(导航栏,视图等).

在promise对象解析之前,延迟子组件初始化的最佳做法是什么?

这是我在Vue应用程序对象中的内容:

beforeCreate: function(){
    // If token or name is not set, unset user client
    var userToken = localStorage.userToken;
    var userName = localStorage.userName;
    if (userToken == undefined || userName == undefined) {
      StoreInstance.commit('unsetUserClient');
      // I WANT TO RESOLVE HERE
      return;
    }

    // If token and name is set, verify token
    // This one makes an HTTP request
    StoreInstance.dispatch({type: 'verifyToken', token: userToken}).then((response) => {
      // I WANT TO RESOLVE HERE …
Run Code Online (Sandbox Code Playgroud)

vue.js vue-resource vuejs2

9
推荐指数
1
解决办法
5841
查看次数

如何在vue-resource http拦截器内重定向用户?

我想在有401时重定向用户,但我无法router从这个上下文访问:

  Vue.http.interceptors.push(function(request, next) {
    // continue to next interceptor
    next(function(response) {
        if(response.status == 401){
            //redirect user here
            //tried: Vue.$router and Vue.$route 
        }

    });
  });
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

使用:Vue-router和Vue-resource

vue-resource vue-router vuejs2

8
推荐指数
1
解决办法
2923
查看次数

另一个ajax里面的vue js ajax正在获取数据而不是渲染视图

有一种情况我必须mounted在vuejs中的第一个ajax(在函数中)之后得到额外的数据,我已经把第二个ajax置于第一个ajax的if条件和内部success函数中!

它工作正常,我在Vue Devtools中看到chrome中的数据,但数据不会在视图中呈现.

伪代码:

var vm = new Vue({
         el: '#messages',
        data: {
            participants: [],
            active_conversation: '',
            messages: []
        },

        methods: {

            getParticipants: function () {
                   return this.$http.post('message/get-participants').then(
                    function (response) {

                        vm.participants = response.data.participants;
                        // if there is a conversation_id param in url
                        if (getUrlParameterByName('conversation_id')) {
                             // Second Ajax Is Called Here inside First Ajax
                             return vm.getConversationMessages (getUrlParameterByName('conversation_id')); // this ajax call is getting data but not showing in view  
                        }
                    }

            },

           getConversationMessages …
Run Code Online (Sandbox Code Playgroud)

javascript ajax vue.js vue-resource vuejs2

8
推荐指数
1
解决办法
702
查看次数

使用Vuex进行API调用的正确方法是什么?

我有一个Vue Webpack应用程序与Vuex(我是两个新人,来自Ember世界).我目前已经设置使用vue-resource和两个文件,如下所示:

/src/store/api.js

import Vue from 'vue';
import { store } from './store';

export default {
  get(url, request) {
    return Vue.http
      .get(store.state.apiBaseUrl + url, request)
      .then(response => Promise.resolve(response.body))
      .catch(error => Promise.reject(error));
  },
  post(url, request) {
    return Vue.http
      .post(store.state.apiBaseUrl + url, request)
      .then(response => Promise.resolve(response))
      .catch(error => Promise.reject(error));
  },
  // Other HTTP methods removed for simplicity
};
Run Code Online (Sandbox Code Playgroud)

然后我将上面的api.js文件导入到我的/src/store/store.js文件中,如下所示:

import Vue from 'vue';
import Vuex from 'vuex';
import Api from './api';

Vue.use(Vuex);

// eslint-disable-next-line
export const store = new Vuex.Store({ …
Run Code Online (Sandbox Code Playgroud)

javascript vue.js vue-resource vuex

8
推荐指数
1
解决办法
5470
查看次数