一.前端解决跨域(修改交互中接口 + vue3中vue.config.js):
1.修改交互中接口:
//使用axios来获取后端接口,记得在script中进行引入axios
//后端提供的完整接口为: http://localhost:8081/hello
//此处的接口直接用 /hello
(省去地址原因是会在vue.config.js中进行配置proxy代理,而代理就直接指向http://localhost:8081)
(所以我们无需再写前缀)
axios.post('/hello').then(res => {
console.log('测试测试测试' + res + '测试测试测试')
})
2.修改vue3中vue.config.js
module.exports = {
devServer: {
// 使用proxy(代理)的方式,
// http://127.0.0.1:8081/ 为后端服务器运行的端口
proxy: 'http://127.0.0.1:8081/',
}
},
二.后端解决跨域(修改交互中接口 + @CrossOrigin注解):
1.修改交互中接口:
//使用axios来获取后端接口,记得在script中进行引入axios
//后端提供的完整接口为: http://localhost:8081/hello
//此处的接口直接用后端提供的 http://localhost:8081/hello
(因为后端来解决跨域问题,前端不需要自己处理,直接用完整接口就好了)
axios.post('http://localhost:8081/hello').then(res => {
console.log('测试测试测试' + res + '测试测试测试')
})
2.在后端中添加@CrossOrigin(origins = "*")
//此处是Springboot,自己在里边新建了一个目录为controller,并且放入了LiveController.java的文件,下面就是整体的java代码,仅用于测试解决跨域问题
@RestController
@CrossOrigin(origins = "*") //此处解决跨域问题(origins = "*"中的 * 是允许任何来源进行访问)
public class LiveController {
// 一个测试的api接口
@RequestMapping(value = "/hello")
public String index(){
return "hello world";
}
}