axios的基本使用和vue腳手架自帶的跨域問題解決
1. axios
1.1 導入axios
npm i axios
1.2 創建serve1.js
serve1.js
const express = require('express')
const app = express()app.use((request,response,next)=>{console.log('有人請求服務器1了');console.log('請求來自于',request.get('Host'));console.log('請求的地址',request.url);next()
})app.get('/students',(request,response)=>{const students = [{id:'001',name:'tom',age:18},{id:'002',name:'jerry',age:19},{id:'003',name:'tony',age:120},]response.send(students)
})
//監聽5000端口
app.listen(5000,(err)=>{if(!err) console.log('服務器1啟動成功了,請求學生信息地址為:http://localhost:5000/students');
})
App.vue
<script>
import axios from 'axios'
export default {name: 'App',components: {},mounted() {//發送請求,注意,請求的端口是8080,而我們服務器監聽的是5000端口axios.get('http://localhost:8080/students').then( response => {console.log(response.data)}).catch( error => {console.log(error.message)})}
}
</script>
1.3 執行node命令,打開服務監聽
node serve1
1.4 啟動vue項目
npm run serve
結果:
2. vue腳手架自帶的跨域問題解決
關于跨域問題的具體說明和其他解決方案見:什么是跨域?跨域解決方法-CSDN博客
想通過vue腳手架自帶的跨域解決,需要在 vue.config.js 中配置 devServer
2.1 基本配置
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({devServer: {//配置serve1.js對應監聽的端口proxy: 'http://localhost:5000'}
})
此時,需要重新運行vue項目
npm run serve
就能在控制臺上看到請求的結果了,結果:
2.2 詳細配置
詳細配置可以精準控制自己本次請求需不需要代理轉發
vue.config.js
//方式二:可以精準控制,看看自己本次請求需不需要代理devServer: {proxy: {//要代理需要加 api 前綴(http://localhost:XXX/api/xxxx),配合pathRewrite屬性使用'/api': { target: 'http://localhost:5000',pathRewrite: {'^/api':''}, //匹配端口號后面以/api開頭的信息,將其變為空changeOrigin: true, //控制請求頭中的host,服務器收到的是改變后的host信息}}}
App.vue
<script>
import axios from 'axios'
export default {name: 'App',components: {},mounted() {//發送請求,注意,請求的端口是8080,而我們服務器監聽的是5000端口//注意,請求的url是 http://localhost:8080/api/students//配合vue.config.js中配置的pathReWrite可以將/api去掉//如果我們加了/api就是需要代理轉發,沒加則不需要axios.get('http://localhost:8080/api/students').then( response => {console.log(response.data)}).catch( error => {console.log(error.message)})}
}
</script>
結果: