vue-resource获取到数据,但执行了失败回调

  • 使用vue-resource发送get请求,可以在浏览器network中看到请求的数据,但接下来的代码却执行的失败回调

代码:

/*重新生成的一个新项目,重现了原来的问题,方便调试*/
/*生成之后只修改了三个文件*/
/*
*    1. app.vue 一个按钮来触发请求即可
*/
<template>
  <div id="app">
    <input type="button" value="get" @click="reqGet">
  </div>
</template>
<script>
...
  methods : {
    reqGet () {
      this.$http.get("/all").then((res) => {
        console.log("success");
      },(res)=>{
        console.log("fail");
      })
    }
  }
...
</script>

/*
*    2.main.js 使用vue-resource
*/
...
import vueResource from 'vue-resource'
Vue.use(vueResource);
...
/*
*    3.webpack.config.js 添加配置
*/
...
devServer:{
...
    proxy: {
      '/api':{
        target: 'http://localhost:8848',
        pathRewrite: {
          '/api': ''
        }
      }
    }
 }
...

终端输出:

clipboard.png

network:

clipboard.png

  • 可以看到获取的数据,但是执行的是失败回调,输出了'fail'
阅读 3.8k
3 个回答

那就解决跨域问题咯,我一会根据你webpack-simple的配置帮你加一个proxyTable的功能。


webpack.config.js
var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true,
    // 这里是新加的代码--------------------
    proxy: {
      '/api':{
        target: 'http://localhost:7001',
        pathRewrite: {
          '/api': ''
        }
      }
    }
    //----------------------------------
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

我是用你说的那个脚手架直接生成的,在这个基础上直接加的proxy,还有什么疑问吗?

console里面不是写的很清楚,你跨域了么

这不是跨域的问题,而是你get的url 怎么被缓存了,返回的状态码是 304,
估计vue-resource 只让 200 的才走success

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题