Vue利用axios發(fā)送請求并代理請求的實現(xiàn)代碼
由于瀏覽器的同源策略,發(fā)送請求時常常遇到跨域問題,一種解決辦法是讓后端配置跨域,還有一種就是使用代理(與前端工程一起啟動,同一個端口),因為代理不是通過瀏覽器發(fā)送的,所以不受同源策略的限制
服務器代碼
用SpringBoot工程(端口為8082)簡單寫了一個Controller層,用于·接收前端發(fā)來的請求,并返回數(shù)據(jù),前端請求
http://localhost:8082/students 時會返回學生列表數(shù)據(jù),訪問 http://localhost:8082/cars 時會返回汽車列表數(shù)據(jù)
import com.example.pojo.Car;
import com.example.pojo.Student;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestController {
private List<Student>studentList=List.of(
Student.builder().id("001").name("張三").age(Short.valueOf("18")).build(),
Student.builder().id("002").name("李四").age(Short.valueOf("19")).build(),
Student.builder().id("003").name("王五").age(Short.valueOf("20")).build()
);
private List<Car>carList=List.of(
Car.builder().id("001").name("奧迪").price(100000F).build(),
Car.builder().id("002").name("瑪莎拉蒂").price(500000F).build(),
Car.builder().id("003").name("奔馳").price(300000F).build()
);
@GetMapping("/students")
public List<Student>getStudentList(){
return studentList;
}
@GetMapping("/cars")
public List<Car>getCarList(){
return carList;
}
}前端代碼
通過配置代理進行請求的轉(zhuǎn)發(fā),實現(xiàn)跨域訪問,在vue.config.js文件中配置如下代碼
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
//開啟代理服務器
devServer:{
proxy: {
'/api': {
target: 'http://localhost:8082/', // 你想要代理到的地址
pathRewrite: {
'^/api': '/' // 重寫路徑,將 /api 替換為 /
}
}
}
}
})通過axios發(fā)送請求,先在終端輸入 npm i axios 引入axios的依賴包,然后通過一下代碼發(fā)送請求
axios.get("/api/students")
.then(
//請求成功的回調(diào)函數(shù)
response=>{
this.studentList=response.data
},
//請求失敗的回調(diào)函數(shù)
err=>{
alert(err.message)
}
)到此這篇關(guān)于Vue利用axios發(fā)送請求并代理請求的文章就介紹到這了,更多相關(guān)Vue axios發(fā)送請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue內(nèi)置組件component--通過is屬性動態(tài)渲染組件操作
這篇文章主要介紹了vue內(nèi)置組件component--通過is屬性動態(tài)渲染組件操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
創(chuàng)建項目及包管理yarn create vite源碼學習
這篇文章主要為大家介紹了創(chuàng)建項目及包管理yarn create vite源碼學習分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09

