一篇搞定vue请求和跨域

  vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现

  axios是一个基本Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护

axios发送AJAX请求

  安装axios

  • npm install axios -S

  基本用法

  • axios([options])
  • axios.get(url[,options])  传参方式:1.通过url 传参   2.通过params选项传参
  • axios.post(url,data,[options])  axios默认发送数据时,数据格式是Request Payload(也就是对象传入,后台接收json数据),并非我们常用的Form Data格式(字符串拼接参数的形式传入),所以参数必须要以键值对形式传递,不能以json形式传参,传参方式:
  1. 自己拼接为键值对
  2. 使用transformRequest,在请求发送前将请求数据进行转换
  3. 如果使用模块化开发,可以使用qs模块进行转换
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>发送AJAX请求</title>
	<script src="js/vue.js"></script>
	<script src="js/axios.min.js"></script>
	<script src="js/vue-resource.min.js"></script>
	<script>
		window.onload=function(){
			new Vue({
				el:‘#itany‘,
				data:{
					user:{
						// name:‘alice‘,
						// age:19
					},
					uid:‘‘
				},
				methods:{
					send(){
						axios({
							method:‘get‘,
							url:‘user.jsonaaa‘
						}).then(function(resp){
							console.log(resp.data);
						}).catch(resp => {
							// console.log(resp);
							console.log(‘请求失败:‘+resp.status+‘,‘+resp.statusText);
						});
					},
					sendGet(){
						// axios.get(‘server.php?name=tom&age=23‘)
						axios.get(‘server.php‘,{
							params:{
								name:‘alice‘,
								age:19
							}
						})
						.then(resp => {
							console.log(resp.data);
						}).catch(err => {
							console.log(‘请求失败:‘+err.status+‘,‘+err.statusText);
						});
					},
					sendPost(){
						// axios.post(‘server.php‘,{
						// 		name:‘alice‘,
						// 		age:19
						// })
						// axios.post(‘server.php‘,‘name=alice&age=20&‘) //方式1
						axios.post(‘server.php‘,this.user,{
							transformRequest:[
								function(data){
									let params=‘‘;
									for(let index in data){
										params+=index+‘=‘+data[index]+‘&‘;
									}
									return params;
								}
							]
						})
						.then(resp => {
							console.log(resp.data);
						}).catch(err => {
							console.log(‘请求失败:‘+err.status+‘,‘+err.statusText);
						});
					},
					getUserById(uid){
						axios.get(`https://api.github.com/users/${uid}`)
						.then(resp => {
							// console.log(resp.data);
							this.user=resp.data;
						});
					},
					sendJSONP(){
						//https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a
						this.$http.jsonp(‘https://sug.so.360.cn/suggest‘,{
							params:{
								word:‘a‘
							}
						}).then(resp => {
							console.log(resp.data.s);
						});
					},
					sendJSONP2(){
						//https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1420_21118_17001_21931_23632_22072&req=2&csor=1&cb=jQuery110208075694879886905_1498805938134&_=1498805938138
						this.$http.jsonp(‘https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su‘,{
							params:{
								wd:‘a‘
							},
							jsonp:‘cb‘ //百度使用的jsonp参数名为cb,所以需要修改
						}).then(resp => {
							console.log(resp.data.s);
						});
					}
				}
			});
		}
	</script>
</head>
<body>
	<div id="itany">
		<button @click="send">发送AJAX请求</button>

		<button @click="sendGet">GET方式发送AJAX请求</button>

		<button @click="sendPost">POST方式发送AJAX请求</button>
		<hr>
		<br>

		GitHub ID: <input type="text" v-model="uid">
		<button @click="getUserById(uid)">获取指定GitHub账户信息并显示</button>
		<br>
		姓名:{{user.name}} <br>
		头像:<img :src="user.avatar_url" >

		<hr>

		<button @click="sendJSONP">向360搜索发送JSONP请求</button>

		<button @click="sendJSONP2">向百度搜索发送JSONP请求</button>

	</div>
</body>
</html>

  另外axios不是全局组件,需要使用时,在每个文件都要引入,如果想达到全局效果,可以在main.js用原型进行绑定Vue.prototype.$http=axios

Proxy代理

  对于前后端分离模式下,前端请求后端存在跨域问题,除了后端主动设置允许跨域请求的类型,前端也可使用proxy代理来转发请求实现跨域

  

  项目准备

  • vue init webpack proxy-demo
  • cd proxy-demo
  • npm install
  • npm install axios -S
  • npm run dev

  

  在下面文件下的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: {
            ‘/flask-api‘: {//前端路由匹配模式
                target: ‘http://localhost:9001‘,  //后端请求服务域名和端口
                changeOrigin: true,   //设置请求头
                pathRewrite: {
                    ‘^/flask-api‘: ‘/‘   //路径重写  前端/flask-api 对应 后端/
                },
            }
        },

        // 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: true,  //运行npm run dev 打开浏览器
        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
    }
}

  就拿login举例,前端localhost:8080/flask-api/login  --> 后端http://localhost:9001/login,而在用axios发送请求时,不用写localhost:8080,直接写/flask-api/login就可以了

<script>
import axios from "axios";

export default {
  name: "App",
  mounted() {
    axios
      .get("/flask-api/task/get")
      .then(resp => {
        console.log(resp.data);
      })
      .catch(err => {
        console.log("request fail");
      });
  },
  methods: {
    send() {
      axios
        .post("/flask-api/task/get", { "hello": "hello" })
        .then(resp => {
          console.log(‘sucees‘)
          // this.$message.success("success");
        })
        .catch(err => {
          console.log(err);
          console.log(err.status);
          console.log(err.statusText);
          console.log("request fail");
        });
    }
  }
};
</script>

  

其他

 axios本身并不支持发送跨域请求,需要使用vue-resource发送跨域请求

  安装

  • npm install vue-resource -S

  基本用法

  使用this.$http发送请求
    this.$http.get(url, [options])
    this.$http.head(url, [options])
    this.$http.delete(url, [options])
    this.$http.jsonp(url, [options])
    this.$http.post(url, [body], [options])
    this.$http.put(url, [body], [options])
    this.$http.patch(url, [body], [options])

原文地址:https://www.cnblogs.com/xinsiwei18/p/9415213.html

时间: 2024-08-29 08:04:13

一篇搞定vue请求和跨域的相关文章

vue开发之跨域请求,请求头not allowed by Access-Control-Allow-Headers,后端cookie session值取不到(二)

原因:你本地的请求ajax的get和post请求:如果你的请求头内放一些可用验证数据Token的时候就会存在跨域请求这是浏览器所不允许的问题: 方案一:后台的接口请求模式都写成jsonp请求,前端去调用: 特点:是一种非正式传输协议,该协议的一个要点就是允许用户传递一个callback 或者开始就定义一个回调方法,参数给服务端,然后服务端返回数据时会将这个callback 参数作为函数名来包裹住JSON数据,这样客户端就可以随意定制自己的函数来自动处理返回数据了. 缺点:它只支持GET请求而不支

JavaScript之Ajax-7 Ajax跨域请求(Ajax跨域概述、Ajax跨域实现)

一.Ajax跨域概述 同源策略 - 同源策略(Same origin policy)是一种约定,它是浏览器的核心也最最基本的核心.如果少了同源策略,则浏览器的正常功能可能都会收到影响.可以说Web是构建在同源策略基础上的,浏览器只是针对同源策略的一种实现 - 它是由 Netscape 提出的一个著名的安全策略 - 现在所有支持 JavaScript 的浏览器都会使用这个策略 - 所谓同源策略是指,域名.协议.端口相同 域名概述 - 域名(Domain Name) 是由一串用点分隔的名字组成的In

jQuery跨域请求,跨域Post提交数据的方法(.net/SQL技术交流群206656202 入群需注明博客园) - 思...

jQuery跨域请求,跨域Post提交数据的方法(.net/SQL技术交流群206656202 入群需注明博客园) - 思... 无聊透顶,网上看看技术文章吸收下精华,无意中发现很多开发人员在跨域请求方面很是疑惑,本人整理了一下曾经写过的代码供苦苦寻找解决方案的IT人一点灵感,如果认为自己是高手呢那么您就可以潇洒的飘过了~~废话不说了免得招人烦~~ 一.get方式实现跨域请求 这里我使用jQuery.getJSON()函数实现      a站点 http://bj.xxxx.com.aspx 请

odoo Controller接口开发 POST请求的跨域问题解决方法

odoo Controller接口开发 POST请求的跨域问题解决方法 1.odoo Controller接口开发,前端在请求的时候会发生跨域问题,报错信息如下:Function declared as capable of handling request of type 'json' but called with a request of type 'http' 2.解决方法如下: odoo官网给的参数解释: cors – The Access-Control-Allow-Origin c

vue proxyTable 接口跨域请求调试(五)

在不同域之间访问是比较常见,在本地调试访问远程服务器....这就是有域问题. VUE解决通过proxyTable: 在 config/index.js 配置文件中 dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', //proxyTable: {}, proxyTable: proxyConfig.prox

Vue--axios:vue中的ajax异步请求(发送和请求数据)、vue-resource异步请求和跨域

跨域原理: 一.使用axios发送get请求 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-eq

从零开始学 Web 之 Vue.js(四)Vue的Ajax请求和跨域

大家好,这里是「 从零开始学 Web 系列教程 」,并在下列地址同步更新...... github:https://github.com/Daotin/Web 微信公众号:Web前端之巅 博客园:http://www.cnblogs.com/lvonve/ CSDN:https://blog.csdn.net/lvonve/ 在这里我会从 Web 前端零基础开始,一步步学习 Web 相关的知识点,期间也会分享一些好玩的项目.现在就让我们一起进入 Web 前端学习的冒险之旅吧! 一.Vue发送Aj

AJAX请求和跨域请求详解(原生JS、Jquery)

一.概述 AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术. AJAX = 异步 JavaScript 和 XML,是一种用于创建快速动态网页的技术.通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新.传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面. 本博客实验环境: python:2.7.11 web框架:tonado jquery:2.1.1 二.“伪”AJAX 由于

关于AJAX请求的跨域问题以及JSONP的示例

一般情况下出于安全考虑,ajax是不能跨域请求的,只能请求本服务器的数据,即同源请求,但完事皆有可能,处于对开发的要求越来越复杂,跨域请求这种事情当然是可以解决的,下面即是转载自一位大佬的随笔 链接:https://www.cnblogs.com/caijunjun/p/6665317.html 看了上篇文章后,肯定是还有点晕的,毕竟介绍的比较多,但是讲的还是比较简单的,下面这篇文章则是一位大佬写的关于JSONP的跨域请求的示例 链接:http://blog.csdn.net/u01460718