Home Web Front-end Vue.js How vue.js sends a request

How vue.js sends a request

Nov 10, 2020 am 10:37 AM
vue.js send request

Vue.js method of sending requests: 1. Introduce jquery and use [$.ajax()]; 2. Install [vue.resource], the code is [this.$http.get('../ src/data/a.txt')then(function(res)】.

How vue.js sends a request

The operating environment of this tutorial: windows10 system, vue2.5.2, this article is applicable to All brands of computers.

[Related article recommendations: vue.js]

vue.js method of sending requests:

1. vue supports developers to introduce jquery using $.ajax()

1、首先,在 package.json 中添加 jQuery,然后 npm install
 
"dependencies": {
    "jquery": "^3.2.1",
  },
2、在 webpack.config.js ( 这边用的 vue-cli-simple 脚手架 )
 
 // 增加一个plugins
  plugins: [
      new webpack.ProvidePlugin({
          $: "jquery",
          jQuery: "jquery"
      })
   ],
3、最后,在全局(main.js)中去引用
 
import $ from 'jquery'
Copy after login

2. vue.resource (no longer updated after 2.0)

1、 npm 安装 vue-resource
 npm install vue-resource<br>
2、 main.js 中引入
import VueResource from &#39;vue-resource&#39;
Vue.use(VueResource)<br>
3、使用
this.$http.get(&#39;../src/data/a.txt&#39;)
    .then(function(res){
          alert(res.data);
    },function(){
          alert(&#39;false&#39;)
});
Copy after login

3. It is recommended to use axios

//url :绝对路径
 
//1、npm 安装
npm install axios
   
//2、组件 中引入main.js引入
 
import axios from &#39;axios&#39;
Vue.prototype.$http = axios
  
//组件中使用:
this.$http.post() 
Copy after login
---------------------------------------------------------
main.js引入                            迭代补进来的
import Axios from &#39;axios&#39;
// 配置请求信息
var $http = Axios.create({
 baseURL: &#39;请求路径&#39;,
 timeout: &#39;3000&#39;,  //请求超时时间
 headers: {&#39;X-Custom-Header&#39;: &#39;foobar&#39;}     //header传值,例如:Authorization
})
Vue.prototype.$http = $http
组件中使用:
this.$http.post()
----------------------------------------------------------
Copy after login
3、使用
this.$http.get(&#39;url&#39;)
     .then(function(res){
    alert(res);
     })
     .catch(function(err){
    alert(err);
})
this.$http.post(&#39;url&#39;, {
    firstName: &#39;Fred&#39;,
    lastName: &#39;Flintstone&#39;
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
});
Copy after login

axios detailed configuration information is as follows:

{
  // `url` 是用于请求的服务器 URL
  url: &#39;/user&#39;,
 
  // `method` 是创建请求时使用的方法
  method: &#39;get&#39;, // 默认是 get
 
  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: &#39;https://some-domain.com/api/&#39;,
 
  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 只能用在 &#39;PUT&#39;, &#39;POST&#39; 和 &#39;PATCH&#39; 这几个请求方法
  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data) {
    // 对 data 进行任意转换处理
 
    return data;
  }],
 
  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
 
    return data;
  }],
 
  // `headers` 是即将被发送的自定义请求头
  headers: {&#39;X-Requested-With&#39;: &#39;XMLHttpRequest&#39;},
 
  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },
 
  // `paramsSerializer` 是一个负责 `params` 序列化的函数
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: &#39;brackets&#39;})
  },
 
  // `data` 是作为请求主体被发送的数据
  // 只适用于这些请求方法 &#39;PUT&#39;, &#39;POST&#39;, 和 &#39;PATCH&#39;
  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属:FormData, File, Blob
  // - Node 专属: Stream
  data: {
    firstName: &#39;Fred&#39;
  },
 
  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,
 
  // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // 默认的
 
  // `adapter` 允许自定义处理请求,以使测试更轻松
  // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },
 
  // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  auth: {
    username: &#39;janedoe&#39;,
    password: &#39;s00pers3cret&#39;
  },
 
  // `responseType` 表示服务器响应的数据类型,可以是 &#39;arraybuffer&#39;, &#39;blob&#39;, &#39;document&#39;, &#39;json&#39;, &#39;text&#39;, &#39;stream&#39;
  responseType: &#39;json&#39;, // 默认的
 
  // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
  xsrfCookieName: &#39;XSRF-TOKEN&#39;, // default
 
  // `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
  xsrfHeaderName: &#39;X-XSRF-TOKEN&#39;, // 默认的
 
  // `onUploadProgress` 允许为上传处理进度事件
  onUploadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },
 
  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },
 
  // `maxContentLength` 定义允许的响应内容的最大尺寸
  maxContentLength: 2000,
 
  // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
  validateStatus: function (status) {
    return status >= 200 && status < 300; // 默认的
  },
 
  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  // 如果设置为0,将不会 follow 任何重定向
  maxRedirects: 5, // 默认的
 
  // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
  // `keepAlive` 默认没有启用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
 
  // &#39;proxy&#39; 定义代理服务器的主机名称和端口
  // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
  // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
  proxy: {
    host: &#39;127.0.0.1&#39;,
    port: 9000,
    auth: : {
      username: &#39;mikeymike&#39;,
      password: &#39;rapunz3l&#39;
    }
  },
 
  // `cancelToken` 指定用于取消请求的 cancel token
  // (查看后面的 Cancellation 这节了解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}
Copy after login

Related free learning recommendations: javascript (video)

The above is the detailed content of How vue.js sends a request. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

A brief analysis of how to handle exceptions in Vue3 dynamic components A brief analysis of how to handle exceptions in Vue3 dynamic components Dec 02, 2022 pm 09:11 PM

How to handle exceptions in Vue3 dynamic components? The following article will talk about Vue3 dynamic component exception handling methods. I hope it will be helpful to everyone!

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.

See all articles