薰 风 2021-06-26 13:07 采纳率: 63.3%
浏览 264
已采纳

前端vue中一直报跨域,以下如何解决

1接口地址 http://film.glkjjt.com/api/Movie/New  这个地址直接放在浏览器中能运行

2在main.js中的代码

import Vue from "vue";

import App from "./App";

import router from "./router";

import axios from "axios";

Vue.prototype.$http = axios;

axios.defaults.baseURL = "http://film.glkjjt.com/api";

Vue.config.productionTip = false;

new Vue({

  el: "#app",

  router,

  components: { App },

  template: "<App/>"

});

3.在config中index.js中的代码

"use strict";

const path = require("path");

module.exports = {

  dev: {

    assetsSubDirectory: "static",

    assetsPublicPath: "/",

  // 在proxyTable中配置的跨域

    proxyTable: {

      "/api": {

        target: "http://film.glkjjt.com",

        changeOrigin: true,

        pathRewrite: {

          "^/api": ""

        }

      }

    },

    host: "localhost", 

    port: 8080, 

    autoOpenBrowser: false,

    errorOverlay: true,

    notifyOnErrors: true,

    poll: false,

    devtool: "cheap-module-eval-source-map",

    cssSourceMap: true

  },

  build: {

    index: path.resolve(__dirname, "../dist/index.html"),

    assetsRoot: path.resolve(__dirname, "../dist"),

    assetsSubDirectory: "static",

    assetsPublicPath: "/",

    productionSourceMap: true,

    devtool: "#source-map",

    productionGzip: false,

    productionGzipExtensions: ["js", "css"],

    bundleAnalyzerReport: process.env.npm_config_report

  }

};

4在components文件夹中HelloWorld.vue中的代码

template>

  <div class="hello">

    <h1>{{ msg }}</h1>

  </div>

</template>

<script>

export default {

  name: "HelloWorld",

  data() {

    return {

      msg: "Welcome to Your Vue.js App"

    };

  },

// 在生命周期里面发请求

  created() {

    this.$http

      .get("api/Movie/New")

      .then(response => {

        console.log(1);

        console.log(response);

      })

      .catch(error => {

        console.log(2);

        console.log(error);

      });

  }

};

</script>

// 接口文档中发这个get请求不需要参数

5 通过npm run dev运行

在浏览器中出现的报错信息

  • 写回答

2条回答 默认 最新

  • 永远不会太晚 2021-06-26 14:05
    关注

    把axios.defaults.baseURL = "http://film.glkjjt.com/api";删了,配置proxy代理不能设置axios.defaults.baseURL 

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献