需求我們要訪問后台的數據,但因為后台的端口號不一致所以需要實現跨域
未跨域
// 請求接口 后台的接口為5001 我們本地的接口為8080,所以我們需要去到vue.config.js配置跨域 http://localhost:5001/api/ this.$axios.post('http://localhost:5001/api/users/register',this.user) .then(res =>{ // 注冊成功 alert('注冊成功!') this.$router.push('/login') console.log(res) })//在http全局配置了catch所以這邊是不用配置的 }
在當前項目的根路徑下新建一個文件,文件名是固定的 vue.config.js —>proxy
module.exports = { devServer: { open: true, host: 'localhost', port: 8080, https: false, //以上的ip和端口是我們本機的;下面為需要跨域的 proxy: { //配置跨域 '/api': { target: 'http://localhost:5001/api/', //這里后台的地址模擬的;應該填寫你們真實的后台接口 ws: true, changOrigin: true, //允許跨域 pathRewrite: { '^/api': '' //請求的時候使用這個api就可以 } } } } }
跨域頁面使用:
// 請求接口 后台的接口為5001 我們本地的接口為8080,所以我們需要去到vue.config.js配置跨域 http://localhost:5001/api/ this.$axios.post('/api/users/register',this.user) .then(res =>{ // 注冊成功 alert('注冊成功!') this.$router.push('/login') console.log(res) })//在http全局配置了catch所以這邊是不用配置的 }
跨域成功:
hint:只要是修改了配置就一定要重啟項目
————————————————
原文鏈接:https://blog.csdn.net/qq_40190624/article/details/85257610