日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue中ajax同步_Vue处理ajax请求

發布時間:2024/3/24 vue 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue中ajax同步_Vue处理ajax请求 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Ajax請求

1>解決跨域問題

1.1前端解決。只需要在vue.config.js中增加devServer節點增加代理:

const path = require("path");

const resolve= dir =>path.join(__dirname, dir);

const BASE_URL= process.env.NODE_ENV === 'procution' ? '/iview-admin/' : '/'module.exports={

lintOnSave:false,

baseUrl: BASE_URL,

chainWebpack: config=>{

config.resolve.alias.set("@",resolve('src')).set("_c",resolve('src/components'))

},//打包時不生成.map文件

productionSourceMap: false,//跨域配置

devServer: {

proxy:"http://localhost:4000"}

}

1.2后端解決,應用cors(Cross-Origin Resource Sharing)解決。

如果是node環境,可以這樣寫:

app.all("*",(req,res,next)=>{

res.hearder("Access-Control-Allow-Origin","*");

res.hearder("Access-Control-Allow-Headers","X-Requested-With,Content-Type");

res.hearder("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");

});

如果是.net環境,在Global.asax中添加如下代碼片段:

protected void Application_BeginRequest(objectsender, EventArgs e)

{

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");if (HttpContext.Current.Request.HttpMethod == "OPTIONS")

{

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");

HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");

HttpContext.Current.Response.End();

}

}

2>封裝axios

下面用axios模擬一個ajax請求為例來對其進行封裝:

后端采用node.js模擬一個接口,代碼如下:

router.post('getUSerInfo', function(req, res, next) {

console.log('請求成功');

res.status(200).send({

code:200,

data: {

name:"Lison"}

});

});

前端代碼目錄結構:

config/index.js:

export const baseURL =process.env.NODE_ENV== "production"

? "http://production.com":"http://localhost:3000";

lib/axios.js:

import axios from "axios";

import { baseURL } from"@/config";//ES6類的寫法

class HttpRequest {//ES6默認參數

constructor(baseUrl =baseURL) {this.baseUrl =baseUrl;this.queue = {}; //將請求都放到隊列中

}

getInsideConfig() {

const config={

baseURL:this.baseUrl,

hearders: {//}

};returnconfig;

}//封裝攔截器

interceptors(instance, url) {

instance.interceptors.request.use(

config=>{//添加全局的loading

//Object.keys() 方法會返回一個由一個給定對象的自身可枚舉屬性組成的數組

if (!Object.keys(this.queue).length) {//spin.show

}this.queue[url] = true;returnconfig;

},

error=>{returnPromise.reject(error);

}

);

instance.interceptors.response.use(

res=>{delete this.queue[url];

const { data, status }=res;return{ data, status };

},

error=>{delete this.queue[url];returnPromise.reject(error);

}

);

}

request(options) {debuggerconst instance=axios.create();/**

* Object.assign() 方法用于將所有可枚舉屬性的值從一個或多個源對象復制到目標對象。它將返回目標對象。

* const target = { a: 1, b: 2 };

* const source = { b: 4, c: 5 };

* const returnedTarget = Object.assign(target, source);

* console.log(target);

* expected output: Object { a: 1, b: 4, c: 5 }*/options= Object.assign(this.getInsideConfig(), options);this.interceptors(instance, options.url);returninstance(options);

}

}

exportdefault HttpRequest;

api/index.js

import HttpRequest from '@/lib/axios'const axios= newHttpRequest()

exportdefault axios

api/user.js

import axios from "./index";

export const getUserInfo= ({ userId }) =>{debugger

returnaxios.request({

url:"/getUserInfo",

method:"post",

data: {

userId

}

});

};

home.vue:

{{ food }}

請求數據

//@ is an alias to /src

import HelloWorld from "@/components/HelloWorld.vue";

import { getUserInfo } from'@/api/user'exportdefault{

name:"home",

components: {

HelloWorld

},

props: {

food: {

type: String,default: "apple"}

},

beforeRouteEnter(to, from, next) {//在渲染該組件的對應路由被 confirm 前調用

//不!能!獲取組件實例 `this`

//因為當守衛執行前,組件實例還沒被創建

next(vm =>{//若想使用實例,可使用這種方法

console.log(vm);

});

},

beforeRouteLeave(to, from, next) {//const leave = confirm('您確定要離開嗎?')

//if (leave) next()

//else next(false)

next();

},

methods: {getInfo() {

getUserInfo({ userId:21 }).then(res =>{

console.log("res: ", res);

});

}

}

};

總結

以上是生活随笔為你收集整理的vue中ajax同步_Vue处理ajax请求的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。