首页 > 其他分享 >6.Vue中与后端的交互

6.Vue中与后端的交互

时间:2022-11-05 18:00:53浏览次数:52  
标签:function Vue http 请求 交互 端的 https 默认值 data

浏览器的同源策略:不允许向不同源(IP+Port)发送请求或者获取数据
解决跨域的方式:
1. 后端解决:在响应头中添加"Access-Control-Allow-Origin = *"
2. 前端解决
3.服务器代理

 

 

1.使用Jquery中的ajax

1.1 引入JQuery

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>

1.2 发送请求

$.ajax({
                    url: 'http://127.0.0.1:8000/test',  // 请求路径
                    type:'get', // 请求方式
                    data:{}, // 跟随的参数
                    success:(data)=>{
                        this.username = data.username
                    },  // 请求成功之后数据封装在data中
                    error(msg){

                    }// 请求失败
                })

 

2.使用JS自带的fetch

fetch().then(res=>res.json()).then(res=>{
   this.username = username 
})

 

3.使用组件axios(推荐)

3.1 引入axios

<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.js"></script>

3.2 axios的使用

https://www.axios-http.cn/docs/api_intro

  1 // 发起一个post请求
  2 axios({
  3   method: 'post',
  4   url: '/user/12345',
  5   data: {
  6     firstName: 'Fred',
  7     lastName: 'Flintstone'
  8   }
  9 });
 10 
 11 
 12 
 13 {
 14   // `url` 是用于请求的服务器 URL
 15   url: '/user',
 16 
 17   // `method` 是创建请求时使用的方法
 18   method: 'get', // 默认值
 19 
 20   // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
 21   // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
 22   baseURL: 'https://some-domain.com/api/',
 23 
 24   // `transformRequest` 允许在向服务器发送前,修改请求数据
 25   // 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
 26   // 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
 27   // 你可以修改请求头。
 28   transformRequest: [function (data, headers) {
 29     // 对发送的 data 进行任意转换处理
 30 
 31     return data;
 32   }],
 33 
 34   // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
 35   transformResponse: [function (data) {
 36     // 对接收的 data 进行任意转换处理
 37 
 38     return data;
 39   }],
 40 
 41   // 自定义请求头
 42   headers: {'X-Requested-With': 'XMLHttpRequest'},
 43 
 44   // `params` 是与请求一起发送的 URL 参数
 45   // 必须是一个简单对象或 URLSearchParams 对象
 46   params: {
 47     ID: 12345
 48   },
 49 
 50   // `paramsSerializer`是可选方法,主要用于序列化`params`
 51   // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
 52   paramsSerializer: function (params) {
 53     return Qs.stringify(params, {arrayFormat: 'brackets'})
 54   },
 55 
 56   // `data` 是作为请求体被发送的数据
 57   // 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
 58   // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
 59   // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
 60   // - 浏览器专属: FormData, File, Blob
 61   // - Node 专属: Stream, Buffer
 62   data: {
 63     firstName: 'Fred'
 64   },
 65   
 66   // 发送请求体数据的可选语法
 67   // 请求方式 post
 68   // 只有 value 会被发送,key 则不会
 69   data: 'Country=Brasil&City=Belo Horizonte',
 70 
 71   // `timeout` 指定请求超时的毫秒数。
 72   // 如果请求时间超过 `timeout` 的值,则请求会被中断
 73   timeout: 1000, // 默认值是 `0` (永不超时)
 74 
 75   // `withCredentials` 表示跨域请求时是否需要使用凭证
 76   withCredentials: false, // default
 77 
 78   // `adapter` 允许自定义处理请求,这使测试更加容易。
 79   // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
 80   adapter: function (config) {
 81     /* ... */
 82   },
 83 
 84   // `auth` HTTP Basic Auth
 85   auth: {
 86     username: 'janedoe',
 87     password: 's00pers3cret'
 88   },
 89 
 90   // `responseType` 表示浏览器将要响应的数据类型
 91   // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
 92   // 浏览器专属:'blob'
 93   responseType: 'json', // 默认值
 94 
 95   // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
 96   // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
 97   // Note: Ignored for `responseType` of 'stream' or client-side requests
 98   responseEncoding: 'utf8', // 默认值
 99 
100   // `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
101   xsrfCookieName: 'XSRF-TOKEN', // 默认值
102 
103   // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
104   xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
105 
106   // `onUploadProgress` 允许为上传处理进度事件
107   // 浏览器专属
108   onUploadProgress: function (progressEvent) {
109     // 处理原生进度事件
110   },
111 
112   // `onDownloadProgress` 允许为下载处理进度事件
113   // 浏览器专属
114   onDownloadProgress: function (progressEvent) {
115     // 处理原生进度事件
116   },
117 
118   // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
119   maxContentLength: 2000,
120 
121   // `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
122   maxBodyLength: 2000,
123 
124   // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
125   // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
126   // 则promise 将会 resolved,否则是 rejected。
127   validateStatus: function (status) {
128     return status >= 200 && status < 300; // 默认值
129   },
130 
131   // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
132   // 如果设置为0,则不会进行重定向
133   maxRedirects: 5, // 默认值
134 
135   // `socketPath` 定义了在node.js中使用的UNIX套接字。
136   // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
137   // 只能指定 `socketPath` 或 `proxy` 。
138   // 若都指定,这使用 `socketPath` 。
139   socketPath: null, // default
140 
141   // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
142   // and https requests, respectively, in node.js. This allows options to be added like
143   // `keepAlive` that are not enabled by default.
144   httpAgent: new http.Agent({ keepAlive: true }),
145   httpsAgent: new https.Agent({ keepAlive: true }),
146 
147   // `proxy` 定义了代理服务器的主机名,端口和协议。
148   // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
149   // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
150   // `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
151   // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
152   // 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
153   proxy: {
154     protocol: 'https',
155     host: '127.0.0.1',
156     port: 9000,
157     auth: {
158       username: 'mikeymike',
159       password: 'rapunz3l'
160     }
161   },
162 
163   // see https://axios-http.com/zh/docs/cancellation
164   cancelToken: new CancelToken(function (cancel) {
165   }),
166 
167   // `decompress` indicates whether or not the response body should be decompressed 
168   // automatically. If set to `true` will also remove the 'content-encoding' header 
169   // from the responses objects of all decompressed responses
170   // - Node only (XHR cannot turn off decompression)
171   decompress: true // 默认值
172 
173 }
// 发送get请求
axios.get('http://127.0.0.1:8000/test').then(res=>{
  console.log(res.data);  // 后端真正的数据
  this.username = res.data().username
})

//发送post请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 

标签:function,Vue,http,请求,交互,端的,https,默认值,data
From: https://www.cnblogs.com/victor1234/p/16860528.html

相关文章