The content of this article is about the use of asynchronous request data in axios (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
After using Mock to simulate the back-end data, you need to try to request to load the data. Axios was selected for the data request, and it is now recommended to use axios.
axios (https://github.com/axios/axios) is based on HTTP library for promises. As introduced in the official website documentation, npm i After that, just load it in the required components. Personally, I think the charm of coding is that there is more than one way to solve a problem. Sometimes this method is ok in your development environment, but not in my development environment. Therefore, there are various problems, and the solution Questioning methods are also diverse.
Getting started with axios
1. Install
npm i axios -S
2. Import
in the src directory Create a new apis.js file (there will be an api interface as the project is gradually improved. Of course, it can also be named axios.js. The name is for others to understand), and introduce:
import axios from 'axios';
Afterwards, edit the apis.js file and consider encapsulating axios.get or post requests
3. Editing of apis.js file
import axios from 'axios'; const Domain = "http://localhost:8080"; // 定义根域名 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; // 设置post默认的请求头 // 封装 post 请求 export function post(action, params){ return new Promise((resolve, reject) => { // url 判断是测试环境 就要拿 测试环境的域名, 正式环境的就要用 正式域名 let url = Domain + action; axios.post(url, params) .then(response => { resolve(response.data) }) .catch(error => { reject(error) }) }); } // 封装 get 请求 export function get(action, params){ return new Promise((resolve, reject) => { axios.get(Domain + action, params) .then(response => { resolve(response.data) }) .catch(error => { reject(error) }) }); } export default { postData(action, params){ return post(action, params) }, getData(action, params){ return get(action, params) } }
import api from '../../apis.js'; export default { name: "banner", data() { return { bannerList: [] }; }, created(){ this.getBanner(); // 在页面渲染完成即加载 }, methods: { getBanner(){ this.$api.getData('/getBanner').then(val => { this.bannerList = val.imgs; }); } } }
Many components need to request data. It is troublesome to import it every time. After global configuration, there is no need to import it in the component.
在入口文件main.js中引入,之后挂在vue的原型链上: import api from './apis.js'; Vue.prototype.$http = api; 在组件中使用: getBanner(){ this.$http.getData('/getBanner').then(val => { this.bannerList = val.imgs; }); }
Reference in the vuex warehouse file store.js and use the action adding method. Actions can contain asynchronous operations, and mutations can be submitted through actions. Action has an inherent parameter context, but context is the parent of state, including state and getters
import Vue from 'Vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ // 定义状态 state: { banners: { name: 'pic' } }, actions: { // 封装一个 ajax 方法 saveBanner (context) { axios({ method: 'get', url: '/getBanner', data: context.state.banners }) } } })
When sending a request in a component, you need to use this.$store.dispatch to distribute
methods: { getBananer() { this.$store.dispatch('saveBanner') // actions里的方法名 } }
Several methods of asynchronous loading
url: requires parameters of String type, (default is the current page address) to which the request is sent.
type: The parameter is required to be of String type. The request method (post or get) defaults to get.
data: Specifies the data to be sent to the server.
async: Boolean value, indicating whether the request is processed asynchronously. The default is true.
dataType: Parameters required to be String type, data type expected to be returned by the server.
contentType: The parameter is required to be of String type. When sending information to the server, the content encoding type defaults to "application/x-www-form-urlencoded".
Success: The parameter is required to be Function type, and the callback function is called after the request is successful.
error: Parameter of Function type, callback function called after the request fails.
jsonp: Rewrite the string of the callback function in a jsonp.
$(function(){ $('#send').click(function(){ $.ajax({ type: "GET", url: "test.json", data: {username:$("#username").val(), content:$("#content").val()}, dataType: "json", success: function(data){ // handle success } error: function(data){ // handle error } jsonp: "" }); }); });
When the URL requested by Ajax is not local or the address of the same server, the browser will report an error: No 'Access-Control -Allow-Origin' header is present on the requested resource. Origin... Due to the browser's security mechanism, URL addresses under different servers cannot be called. Based on this, jQuery.ajax gives a jsonp solution: Set the data type returned by the server to jsonp.
$(function(){ $('#send').click(function(){ $.ajax({ type: "GET", url: "test.json", data: {username:$("#username").val(), content:$("#content").val()}, dataType: "jsonp", // jsonp格式 success: function(data){ // handle success } error: function(data){ // handle error } jsonp: "callback" }); }); });
However, jsonp is an unofficial method, and this method only supports get requests, which is not as safe as post requests. In addition, jsonp requires the cooperation of the server. If we are accessing a third-party server and we do not have the permission to modify the server, then this method is not feasible.
ue-resource is a plug-in for Vue.js. It can initiate requests and process responses through XMLHttpRequest or JSONP. vue-resource is small in size and supports mainstream browsers. However, vue will no longer be updated after 2.0. You Dashen recommends using axios.
{ // GET /someUrl this.$http.get('/someUrl').then(response => { // get body data this.someData = response.body; }, response => { // error callback }); }
Similarly, due to the browser’s security mechanism, vue-resource also faces cross-domain request issues. The solution is as follows: Configure the proxy table in the config/index.js file under the vue project:
dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { // 新增,解决跨域请求问题 '/api': { target: 'http://192.168.1.103:8080/', changeOrigin: true, pathRewrite: { '`/api': '/' } }, secure: false }, target中写你想要请求数据的地址的域名
is the same as vue-resource, in the vue project The proxy proxyTable is configured in the config/index.js file under:
dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { // 新增,解决跨域请求问题 '/api': { target: 'http://192.168.1.103:8080/', changeOrigin: true, pathRewrite: { '`/api': '/' } }, secure: false },
However, with the two methods of vue-resource and axios, the proxy table may still be reported: No 'Access-Control-Allow-Origin' The problem of header is present on... requires the back-end server to cooperate with the settings:
header("Access-Control-Allow-Origin", "*"); header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
The above is the detailed content of Usage of axios asynchronous request data (code example). For more information, please follow other related articles on the PHP Chinese website!