1. 在 config/index.js 配置文件中配置proxyTable

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = {
dev: { // Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/apis': {
// 测试环境
target: 'http://www.thenewstep.cn/', // 接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite重写的,
}
}
}, // Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- /**
* Source Maps
*/ // https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map', // If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true, cssSourceMap: true
}, build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'), // Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/', /**
* Source Maps
*/ productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map', // Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}

2. fetch实现跨域请求

在根组件App.vue里面发送请求

// 1. 模板:html结构 有且只有一个根标签
<template>
<div id="app">
<!-- 使用路由实现跳转 注意:to里面写的是路由的名字 -->
<ul>
<li><router-link to="/">home</router-link></li>
<li><router-link to="/Users">Users</router-link></li>
</ul>
<!-- 进入首页默认加载的路由 -->
<router-view></router-view>
</div>
</template> //2. 行为:处理逻辑
<script> export default {
name: 'App',//组件App.vue的名字
data () {
return { }
},
//实现跨域请求
created(){
//fetch实现跨域请求
fetch("/apis/test/testToken.php",{
method:"POST",
headers:{
token:"f4c902c9ae5a2a9d8f84868ad064e706" },
body:JSON.stringify({username:"lgs",password:"123"})
}).then(result=>{
// console.log(result)
//解析数据
return result.json()
}).then(data =>{
//打印数据
console.log(data);
})
}
}
</script> //3. 样式:解决样式
<style scoped>
h1
{
color:purple;
}
</style>

响应结果:

3. axios实现跨域请求

3.1 停止项目,安装axiosnpm install axios,然后重启项目npm run dev

3.2 在main.js里面引入axios,配置全局使用axios,设置token和请求头

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue' //导入vue
import VueRouter from 'vue-router' //引入路由
import VueResource from 'vue-resource' //引入vue-resource
import axios from 'axios' //引入axios
import App from './App' //导入根组件App.vue
import Users from './components/Users'//导入组件Users.vue
import Home from './components/Home'//导入组件Users.vue //全局使用axios
Vue.prototype.$axios = axios
//设置token
axios.defaults.headers.common['token'] = "f4c902c9ae5a2a9d8f84868ad064e706"
//设置请求头
axios.defaults.headers.post["Content-type"] = "application/json" Vue.config.productionTip = false
//引入路由后使用路由,这样就可以在任何组件中使用路由了
Vue.use(VueRouter)
//引入vue-resource后使用vue-resource,这样就可以在任何组件中使用http了
Vue.use(VueResource)
//配置路由
const router = new VueRouter(
{
routes : [
//配置路由跳转到Home这个组件
{path:"/",component:Home},
//配置路由跳转到Users.vue这个组件
{path:"/Users",component:Users}
],
//去掉地址栏的"/#/"
mode : "history"
}
) /* eslint-disable no-new */
new Vue({ //实例化一个vue对象
router,//使用路由
el: '#app', //index.html的根元素app
components: { App },//注册根组件App.vue才能使用
template: '<App/>'//VUE模板使用,可以是组件、html标签等
})

3.2  在根组件App.vue里面发送请求

// 1. 模板:html结构 有且只有一个根标签
<template>
<div id="app">
<!-- 使用路由实现跳转 注意:to里面写的是路由的名字 -->
<ul>
<li><router-link to="/">home</router-link></li>
<li><router-link to="/Users">Users</router-link></li>
</ul>
<!-- 进入首页默认加载的路由 -->
<router-view></router-view>
</div>
</template> //2. 行为:处理逻辑
<script> export default {
name: 'App',//组件App.vue的名字
data () {
return { }
},
//实现跨域请求
created(){
//fetch实现跨域请求
// fetch("/apis/test/testToken.php",{
// method:"POST",
// headers:{
// token:"f4c902c9ae5a2a9d8f84868ad064e706" // },
// body:JSON.stringify({username:"lgs",password:"123"})
// }).then(result=>{
// // console.log(result)
// //解析数据
// return result.json()
// }).then(data =>{
// //打印数据
// console.log(data);
// })

//axios实现跨域请求
this.$axios.post("/apis/test/testToken.php",{
username:"lgs",password:"123"
}).then(data=>
{
console.log(data)
})
}
}
</script> //3. 样式:解决样式
<style scoped>
h1
{
color:purple;
}
</style>

响应结果:

VUE系列三:实现跨域请求(fetch/axios/proxytable)的更多相关文章

  1. vue.js学习之 跨域请求代理与axios传参

    vue.js学习之 跨域请求代理与axios传参 一:跨域请求代理 1:打开config/index.js module.exports{ dev: { } } 在这里面找到proxyTable{}, ...

  2. vue-cli3中axios如何跨域请求以及axios封装

    1. vue.config.js中配置如下 module.exports = { // 选项... // devtool: 'eval-source-map',//开发调试 devServer: { ...

  3. Vue.js 2.0 跨域请求数据

    Vuejs由1.0更新到了2.0版本.HTTP请求官方也从推荐使用Vue-Resoure变为了 axios .接下来我们来简单地用axios进行一下异步请求.(阅读本文作者默认读者具有使用npm命令的 ...

  4. web三种跨域请求数据方法

    以下测试代码使用php,浏览器测试使用IE9,chrome,firefox,safari <!DOCTYPE HTML> <html> <head>     < ...

  5. flask插件系列之flask_cors跨域请求

    前后端分离在开发调试阶段本地的flask测试服务器需要允许跨域访问,简单解决办法有二: 使用flask_cors包 安装 pip install flask_cors 初始化的时候加载配置,这样就可以 ...

  6. 基于vue移动音乐webapp跨域请求失败的问题解决

    在学习一位vue大牛的课程<VUE2.0移动端音乐App开发>时,由于vue的版本原因遇到了一些问题 这是其中之一,花费了很多的时间去解决 虽然搞定了这个问题,但是很多东西理解也不是很到位 ...

  7. Django 跨域请求 解决 axios 未完待续

    import django import os # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "untitled5. ...

  8. vue-cli项目开发/生产环境代理实现跨域请求+webpack配置开发/生产环境的接口地址

    一.开发环境中跨域 使用 Vue-cli 创建的项目,开发地址是 localhost:8080,需要访问非本机上的接口http://10.1.0.34:8000/queryRole.不同域名之间的访问 ...

  9. spring boot跨域请求访问配置以及spring security中配置失效的原理解析

    一.同源策略 同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 什么是源 源[orig ...

随机推荐

  1. Android-一只手指滑动View,另一只手指按Home键,重新进入后View状态无法更新的问题

    上午测试报了一个bug:说是一只手指拖动虚拟摇杆上的View滑块不松,另一只手指点击Home键将App压后台,重新进入的时候,View滑块卡死了. 刚开始看到这个问题感觉很奇怪,因为正常情况下,手指离 ...

  2. CNN及其可解释性

    https://stats385.github.io/readings https://arxiv.org/pdf/1311.2901.pdf A Mathematical Theory of Dee ...

  3. Pycharm 2017.1 激活服务器

    最近发现pycharm激活异常困难 原来的激活码 都不能用了 so 根据网上 教程 自己建了激活服务器 尝试可用服务器 20170504 测试发现 给需要域名 http://www.05nb.com: ...

  4. SVN四部曲之SVN设置详解深入

    想知道不同的设置是干什么用的,你只需将鼠标指针在编辑框/选项框上停留一秒钟...一个帮助提示气泡就会弹出来. 常规设置 图 4.68. 设置对话框,常规设置页面 这个对话框允许你指定自己喜欢的语言,同 ...

  5. excel 添加换行符,去除换行符:

    excel 中添加换行符: :alt+enter 去掉excel中的换行符有三种方法: 注:解决过程中翻阅其他博客,看到如下方式: 1.看到有的说全选后“取消自动换行”,保存后,再打开,依然存在换行符 ...

  6. iOS 减法计算器

    一: 在界面上拖入相应的控件 二: 给每个控件设置关联 //监听按钮的点击 - (IBAction)compute:(id)sender; //第一个文本输入框的值 @property (weak, ...

  7. 一起学习Maven

    Maven是项目构建工具,能根据配置构建起一个项目. Maven中有一个配置文件,叫pom.xml,而pom的全称是Project Object Model,即项目对象模型,它配置的目标对象是项目. ...

  8. hive sequencefile导入文件遇到FAILED: SemanticException Unable to load data to destination table. Error: The file that you are trying to load does not match the file format of the destination table.错误

    hive sequencefile导入文件遇到FAILED: SemanticException Unable to load data to destination table. Error: Th ...

  9. PHP 常见header 状态

    转载:http://blog.csdn.net/mothz/article/details/6029810 <?php //200 正常状态 header('HTTP/1.1 200 OK'); ...

  10. Gridview排序与分页-不使用“DataSourceControl DataSource”的情况下如何分页和排序 ...

    如果你在GridView控件上设置 AllowPaging="true" or AllowSorting="true" 而没有使用使用数据源控件 DataSou ...