前端解决跨域问题
新建server.js
yarn add express
const express = require("express")
const app = new express();
app.get('/user', function(request, response) {
response.send('hello World')
})
app.listen(5000, function() {
console.log("Server is running ....")
})
ip地址就是http:localhost:5000
启动服务 node server.js
新建vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target:'http://localhost:5000', //target代理的就是后端接口
changeOrigin:true,
pathRewrite:{
'^/api': ''
}
}
},
},
}
<script>
import axios from 'axios'
export default {
data() {
return {
}
},
methods: {
getData() {
// 匹配到/api以后直接设置为空
axios.get("/api/user").then(res => {
console.log("res",res)
})
}
},
mounted() {
console.log("axios",axios)
this.getData()
}
}
</script>